<template>
  <el-dialog
    v-model="show"
    width="88vw"
    class="dialog-okr"
    :show-close="false"
    :close-on-click-modal="false"
  >
    <template #header>
      <div class="dialog-okr-header">
        <div class="flex-1 flex items-center" style="line-height: 50px"> {{ title }} </div>
        <div class="flex items-center">
          <el-button type="primary" link :disabled="formLoading" @click="handleSave">
            保存
          </el-button>
          <el-button link @click="show = false"> 关闭 </el-button>
        </div>
      </div>
    </template>
    <template #default>
      <div class="dialog-okr-body" v-loading="formLoading">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="0">
          <el-row :gutter="10">
            <el-col :span="4" :offset="0">
              <el-form-item prop="parentId">
                <el-tree-select
                  v-model="form.parentId"
                  :data="parentNodeList"
                  check-strictly
                  :props="{ value: 'nodeId', label: 'nodeName', children: 'children' }"
                  :render-after-expand="false"
                  placeholder="父节点"
                  clearable
                  :disabled="!!form.nodeId"
                  @change="handleChangeParent"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4" :offset="0">
              <el-form-item prop="nodeName">
                <el-input v-model="form.nodeName" placeholder="请输入节点名称" />
              </el-form-item>
            </el-col>
            <el-col :span="4" :offset="0">
              <el-form-item prop="startTime">
                <el-date-picker
                  v-model="form.startTime"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  placeholder="开始日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4" :offset="0">
              <el-form-item prop="endTime">
                <el-date-picker
                  v-model="form.endTime"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  placeholder="截止日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4" :offset="0">
              <el-form-item prop="executor">
                <el-select
                  v-model="form.executor"
                  placeholder="选择执行人，可多选"
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in userOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id + ''"
                    :disabled="item.status == 1"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" :offset="0">
              <el-form-item prop="dataScope">
                <el-select v-model="form.dataScope" placeholder="选择权限" clearable filterable>
                  <el-option label="公开" :value="1" />
                  <el-option label="仅上级可见" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="relative">
          <el-button
            v-if="okrKey == 'okr'"
            style="position: absolute; right: 10px; top: 10px; z-index: 9"
            type="primary"
            size="small"
            @click="addObjective"
          >
            添加目标
          </el-button>
          <el-button
            v-else-if="okrKey == 'childNode'"
            style="position: absolute; right: 10px; top: 10px; z-index: 9"
            type="primary"
            size="small"
            @click="addChildNode"
          >
            添加子节点
          </el-button>
          <el-tabs v-model="okrKey">
            <el-tab-pane label="目标/关键成果" name="okr">
              <div>
                <div
                  class="flex items-center w-full"
                  v-for="(item, i) in objectList"
                  :key="item.objectiveId"
                  style="padding-bottom: 5px"
                >
                  <div class="flex-1 w-100px">
                    <div class="flex items-center">
                      <el-tooltip content="点击可折叠/展开目标" placement="top" effect="dark">
                        <el-tag
                          type="success"
                          class="mr-10px"
                          @click="item.hideChild = !item.hideChild"
                        >
                          O{{ i + 1 }}
                        </el-tag>
                      </el-tooltip>

                      <el-input
                        v-model="item.objectiveName"
                        placeholder="目标名称"
                        class="flex-1 w-150px"
                        :disabled="!!item.objectiveId"
                      />
                      <el-select
                        v-model="item.executor"
                        placeholder="选择执行人，可多选"
                        multiple
                        clearable
                        collapse-tags
                        filterable
                        style="width: 240px; margin-left: 10px"
                      >
                        <el-option
                          v-for="it in userOptions"
                          :key="it.id"
                          :label="it.name"
                          :value="it.id + ''"
                          :disabled="it.status == 1"
                        />
                      </el-select>
                      <el-select
                        v-model="item.dataScope"
                        placeholder="选择权限"
                        clearable
                        filterable
                        style="width: 120px; margin-left: 10px"
                      >
                        <el-option label="公开" :value="1" />
                        <el-option label="仅上级可见" :value="2" />
                      </el-select>
                      <div class="ml-10px">
                        <el-button type="primary" text @click="AddKR(i)">新增关键成果</el-button>
                        <el-button type="danger" text @click="removeObj(i)">删除目标</el-button>
                      </div>
                    </div>
                    <div v-if="!item.hideChild" style="background: #f0f3fa; padding-bottom: 10px">
                      <div
                        class="ml-50px"
                        v-for="(kr, index) in item.keyResults"
                        :key="kr.keyResultId"
                      >
                        <div class="flex flex-1 items-center pb-5px pt-5px">
                          <el-tag class="mr-10px">KR{{ index + 1 }}</el-tag>
                          <el-select
                            v-model="kr.keyResultName"
                            placeholder="选择或输入关键成果"
                            filterable
                            :props="{ value: 'keyResultId', label: 'keyResultName' }"
                            allow-create
                            :reserve-keyword="false"
                            class="flex-1 w-150px"
                            @change="krChange(i, index)"
                          >
                            <el-option
                              v-for="it in krOptions"
                              :key="it.value"
                              :label="it.label"
                              :value="it.value"
                            />
                          </el-select>
                          <el-button type="danger" text @click="removeKR(i, index)">
                            删除关键成果
                          </el-button>
                        </div>
                        <div class="mt-5px flex items-center">
                          <el-tree-select
                            v-model="kr.source"
                            :data="sourceOptions"
                            :props="defaultProps"
                            check-strictly
                            clearable
                            filterable
                            style="width: 200px"
                            node-key="sourceId"
                            placeholder="请选择渠道"
                          />
                          <!-- <el-radio-group v-model="kr.resultType" class="ml-10px">
                            <el-radio-button :value="1">目标值</el-radio-button>
                            <el-radio-button :value="2">是/否</el-radio-button>
                          </el-radio-group> -->

                          <el-input
                            v-if="kr.resultType == 1"
                            v-model="kr.targetValue"
                            type="number"
                            placeholder="目标值"
                            class="ml-10px"
                            style="width: 120px"
                          />

                          <el-select
                            v-model="kr.executor"
                            placeholder="选择执行人，可多选"
                            multiple
                            clearable
                            filterable
                            collapse-tags
                            collapse-tags-tooltip
                            style="width: 240px; margin-left: 10px"
                          >
                            <el-option
                              v-for="it in userOptions"
                              :key="it.id"
                              :label="it.name"
                              :value="it.id + ''"
                              :disabled="it.status == 1"
                            />
                          </el-select>
                          <el-select
                            v-model="kr.dataScope"
                            placeholder="选择权限"
                            clearable
                            filterable
                            style="width: 120px; margin-left: 10px"
                          >
                            <el-option label="公开" :value="1" />
                            <el-option label="仅上级可见" :value="2" />
                          </el-select>
                          <el-radio-group v-model="kr.isCount" class="ml-10px">
                            <el-radio :label="true" :value="true">参与统计</el-radio>
                            <el-radio :label="false" :value="false">不参与统计</el-radio>
                          </el-radio-group>
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- <div class="w-100px"></div> -->
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="子节点" name="childNode">
              <el-table :data="childNodeList">
                <el-table-column label="名称">
                  <template #default="{ row }">
                    <el-input v-model="row.nodeName" placeholder="子节点名称" />
                  </template>
                </el-table-column>
                <el-table-column label="开始日期" width="160px">
                  <template #default="{ row }">
                    <el-date-picker
                      v-model="row.startTime"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      placeholder="选择日期时间"
                      style="width: 130px"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="截止日期" width="160px">
                  <template #default="{ row }">
                    <el-date-picker
                      v-model="row.endTime"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      placeholder="选择日期时间"
                      style="width: 130px"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="权限" width="160px">
                  <template #default="{ row }">
                    <el-select v-model="row.dataScope" placeholder="请选择" style="width: 130px">
                      <el-option label="公开" :value="1" />
                      <el-option label="仅上级可见" :value="2" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="执行人" width="300px">
                  <template #default="{ row }">
                    <el-select
                      v-model="row.executor"
                      placeholder="选择执行人，可多选"
                      multiple
                      clearable
                      filterable
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in userOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id + ''"
                        :disabled="item.status == 1"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="删除" :width="100">
                  <template #default="{ $index }">
                    <el-button type="danger" text @click="removeChildNode($index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="DialogOkrInfo">
import {
  getAllNodeTree,
  getOkrNodeDetail,
  createOkrNode,
  updateOkrNode,
  getAllOkrPage,
  getDefaultOkrOptions,
  getChannelOptions
} from '@/api/okr/okr'
import { listToTree } from '@/utils/tree'
import { getEmployeeSimpleList } from '@/api/pers/employee'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const show = ref(false)

watch(
  () => show.value,
  (newValue, oldValue) => {
    if (oldValue && !newValue) {
      emit('close')
    }
  }
)

const title = ref('')
const formType = ref('create')

const form = ref({})
const formLoading = ref(false)
const rules = ref({
  nodeName: { required: true, message: '节点名称不可为空', trigger: 'blur' },
  startTime: { required: true, message: '开始日期不可为空', trigger: 'change' },
  endTime: { required: true, message: '截止日期不可为空', trigger: 'change' }
})

const okrKey = ref('okr')

const parentNodeList = ref([])

const childNodeList = ref([])

const userOptions = ref([])
const krOptions = ref([])
const defaultProps = {
  children: 'children',
  label: 'sourceName',
  value: 'sourceId',
  isLeaf: 'leaf'
}
const sourceOptions = ref([])
const objectList = ref([])
function open(type, val, queryType) {
  show.value = true
  title.value = type == 'update' ? '修改Okr' : '新增Okr'
  formType.value = type
  resetForm()
  getEmployeeSimpleList().then((data) => {
    userOptions.value = data
  })
  getAllNodeTree().then((resp) => {
    parentNodeList.value = listToTree(resp.tree, {
      id: 'nodeId',
      pid: 'parentId',
      children: 'children'
    })
  })
  getDefaultOkrOptions().then((resp) => {
    krOptions.value = resp
  })
  getChannelOptions().then((resp) => {
    sourceOptions.value = listToTree(resp, {
      id: 'sourceId',
      pid: 'parentId',
      children: 'children'
    })
  })
  if (val) {
    formLoading.value = true
    try {
      getOkrNodeDetail({
        nodeId: val,
        queryType
      }).then((resp) => {
        form.value = resp
        if (resp.objectives) {
          objectList.value = resp.objectives.map((item) => ({
            ...item,
            keyResults: item.keyResults || []
          }))
        } else {
          objectList.value = []
        }
        childNodeList.value = [...resp.children]
      })
    } finally {
      formLoading.value = false
    }
  }
}
function resetForm() {
  form.value = {
    parentId: undefined,
    nodeName: undefined,
    startTime: undefined,
    endTime: undefined,
    executor: [],
    dataScope: 2
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const formRef = ref()
/** 提交表单 */
const emit = defineEmits(['success', 'close']) // 定义 success 事件，用于操作成功后的回调

function addObjective() {
  objectList.value.push({
    objectiveName: '',
    executor: [],
    keyResults: [],
    dataScope: 2
  })
}

function AddKR(idx) {
  if (!objectList.value[idx].keyResults) {
    objectList.value[idx].keyResults = []
  }
  const obj = objectList.value[idx]
  objectList.value[idx].keyResults.push({
    keyResultName: undefined,
    resultType: 1,
    source: undefined,
    targetValue: undefined,
    process: undefined,
    currentValue: undefined,
    executor: obj.executor,
    dataScope: obj.dataScope,
    isCount: false
  })
}

function removeObj(idx) {
  objectList.value.splice(idx, 1)
}

function removeKR(oIdx, krIdx) {
  objectList.value[oIdx].keyResults.splice(krIdx, 1)
}

function addChildNode() {
  childNodeList.value.push({ dataScope: 2 })
}

function removeChildNode(idx) {
  childNodeList.value.splice(idx, 1)
}

// 读取父节点的OKR，并展示出来
function handleChangeParent() {
  // 通过父节点Id,查询父节点的okr，需要继承
  if (form.value.parentId) {
    getAllOkrPage({ nodeId: form.value.parentId }).then((resp) => {
      objectList.value = resp
    })
  }
}

function getLastDayOfMonth(year, month) {
  // 创建一个日期对象，将月份设置为指定月份的下一个月，日期设置为 0
  const date = new Date(year, month + 1, 0)
  // 返回该日期对象的日期部分，即指定年月的最后一天
  return date.getDate()
}

function krChange(idx, krIdx) {
  const kr = objectList.value[idx].keyResults[krIdx]
  if (kr.keyResultName) {
    const obj = krOptions.value.find((item) => item.value == kr.keyResultName)
    if (obj) {
      kr.isSys = true
    } else {
      kr.isSys = false
    }
  }
}

async function handleSave() {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return

  form.value.executor = form.value.executor || []
  if (form.value.executor.length > 1) {
    message
      .confirm('是否按照当前节点所选的多个执行人自动新增对应的员工节点？', {
        type: 'warning',
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定'
      })
      .then(() => {
        saveOkrData(true)
      })
      .catch(() => {
        saveOkrData(false)
      })
  } else {
    saveOkrData(false)
  }
}

async function saveOkrData(isAutoAddChild = false) {
  // 提交请求
  formLoading.value = true
  try {
    form.value.isAutoAddChild = isAutoAddChild
    form.value.objectives = objectList.value
    form.value.children = childNodeList.value
    if (formType.value === 'create') {
      // 创建的是一级节点,且子节点为空时，自动新增12个月子节点，并且每月添加4周的周子节点
      if (!form.value.parentId) {
        if (form.value.children.length == 0) {
          const defaultTime = new Date(form.value.startTime)
          for (let month = 0; month < 12; month++) {
            form.value.children.push({
              nodeName: `${month + 1}月`,
              startTime: `${defaultTime.getFullYear()}-${String(month + 1).padStart(2, '0')}-01`,
              endTime: `${defaultTime.getFullYear()}-${String(month + 1).padStart(
                2,
                '0'
              )}-${getLastDayOfMonth(defaultTime.getFullYear(), month)}`,
              children: [
                {
                  nodeName: `${month + 1}月第1周`,
                  children: []
                },
                {
                  nodeName: `${month + 1}月第2周`,
                  children: []
                },
                {
                  nodeName: `${month + 1}月第3周`,
                  children: []
                },
                {
                  nodeName: `${month + 1}月第4周`,
                  children: []
                }
              ]
            })
          }
        }
      }
      await createOkrNode(form.value)
      message.success(t('common.createSuccess'))
    } else {
      await updateOkrNode(form.value)
      message.success(t('common.updateSuccess'))
    }
    show.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.dialog-okr {
  .dialog-okr-header {
    display: flex;
    height: 51px;
    min-height: 51px;
    vertical-align: middle;
    justify-content: space-between;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    padding: 0 1.25rem;
  }
  .dialog-okr-body {
    overflow-x: hidden;
    overflow-y: auto;
    min-width: 1064px;
    height: calc(94vh - 85px);
  }
}
</style>
