<script setup name="projectGroup">
import { getCurrentInstance, h, onMounted, reactive, ref } from 'vue'
import { groupDel, groupList, groupSave, groupDetail } from '@/http/apis/performanceEvaluation/evaluationPlan'
import { useRoute } from 'vue-router'
import UserListDialog from '@/pages/performanceEvaluation/evaluationPlan/projectGroup/components/userListDialog.vue'
import PlanProjectDialog from '@/pages/performanceEvaluation/evaluationPlan/projectGroup/components/planProjectDialog.vue'
import { templateTypeList } from '@/http/apis/performanceEvaluation/indicatorTemplate'
import store from '@/store'
const { proxy } = getCurrentInstance(),
  {
    projectTypeOptions
  } = store.dictStore.globalDicts || {},
  formData = ref({
    name: '',
    reAppraisalUsers: [],
    verificationUsers: [],
    projects: [],
    verifyLeader: undefined
  }),
  searchForm = reactive({
    name: undefined
  }),
  formRef = ref(),
  route = useRoute(),
  tableListRef = ref(),
  column = reactive([
    {
      label: '序号',
      type: 'index',
      width: '80'
    },
    {
      label: '分组名称',
      key: 'name',
      prop: 'name',
      minWidth: '120',
      showOverflowTooltip: true
    },
    {
      label: '复评人员',
      key: 'reAppraisalUsers',
      prop: 'reAppraisalUsers',
      render: row => h('span', row.reAppraisalUsers?.map(i => i?.username).join('、'))
    },
    {
      label: '核查人员',
      key: 'verificationUsers',
      prop: 'verificationUsers',
      render: row => h('span', row.verificationUsers?.map(i => i?.username).join('、'))
    },

    {
      label: '创建时间',
      key: 'createOn',
      prop: 'createOn',
      width: '150'
    },
    {
      label: '操作',
      slot: 'action',
      width: '200',
      fixed: 'right'
    }
  ]),
  rules = {
    name: [
      { required: true, message: '请填写', trigger: 'blur' }
    ],
    projects: [
      { required: true, message: '请选择', trigger: 'blur' }
    ],
    reAppraisalUsers: [
      { required: true, message: '请选择', trigger: 'blur' }
    ],
    verificationUsers: [
      { required: true, message: '请选择', trigger: 'blur' }
    ],
    verifyLeader: [{ required: true, message: '请选择', trigger: 'blur' }]
  },
  column2 = reactive([
    {
      label: '序号',
      type: 'index',
      width: '80'
    },
    {
      label: '项目名称',
      key: 'projectName',
      prop: 'projectName',
      minWidth: '200',
      showOverflowTooltip: true
    },
    {
      label: '预算年度',
      key: 'projectYear',
      prop: 'projectYear',
      width: 80
    },
    {
      label: '项目金额',
      key: 'declareAmount',
      prop: 'declareAmount'
    },
    {
      label: '申报单位',
      key: 'buildOrgName',
      prop: 'buildOrgName'
    },
    {
      label: '项目类型',
      key: 'projectType',
      prop: 'projectType',
      render: row => h('span', projectTypeOptions[row.projectType] || '-'),
      width: 80
    },
    {
      label: '模板类型',
      key: 'templateType',
      prop: 'templateType',
      render: row => h('span', templateTypeListData.value?.find(i => i.id === row.templateType)?.name || '-')
    },
    // {
    //   label: '是否评价',
    //   key: 'isAppraisal',
    //   prop: 'isAppraisal',
    //   render: row => h('span', row.isAppraisal ? '是' : '否'),
    //   width: 80
    // },
    // {
    //   label: '是否复评',
    //   key: 'isReAppraisal',
    //   prop: 'isReAppraisal',
    //   render: row => h('span', row.isReAppraisal ? '是' : '否'),
    //   width: 80
    // },
    {
      label: '操作',
      slot: 'action',
      width: '80',
      fixed: 'right'
    }
  ]),
  data = ref([]),
  getTableData = async (pageParams = tableListRef.value.pageParams) => {
    const res = await groupList(route.query.appraisalId, {
      ...searchForm
    })
    data.value = res.data
    console.log(data)
  },
  delGroup = (row) => {
    proxy.$messageBox
      .confirm(`确定要删除该${row.name}吗?`, '提示！', {
        type: 'warning'
      })
      .then(async () => {
        await groupDel(row.id)
        getTableData()
        proxy.$message.success('删除成功')
      })
  },
  search = () => {
    getTableData()
  },
  reset = () => {
    searchForm.name = undefined
    tableListRef.value.pageParams.pageNumber = 1
    tableListRef.value.pageParams.pageSize = 10
    getTableData()
  },
  dialogVisible = ref(false),
  dialogTitle = ref(''),
  isEdit = ref(true),
  addGroup = async (data, flag) => {
    dialogTitle.value = '新增分组'
    isEdit.value = true
    if (data?.id) {
      isEdit.value = flag
      dialogTitle.value = flag ? '编辑分组' : '分组详情'
      const res = await groupDetail(data.id)
      formData.value = {
        ...res.data,
        reAppraisalUsers: res.data.reAppraisalUsers.map(i => {
          return {
            ...i,
            name: i.username,
            phoneNo: i.mobile,
            orgName: i.empPosUnitName
          }
        }),
        verificationUsers: res.data.verificationUsers.map(i => {
          return {
            ...i,
            name: i.username,
            phoneNo: i.mobile,
            orgName: i.empPosUnitName
          }
        }),
        verifyLeader: res.data.verifyLeader?.employeeCode || ''
      }
    } else {
      formData.value = {}
    }
    dialogVisible.value = true
  },
  // 添加人员
  userFieldName = ref(''),
  userListDialogData = reactive({
    visible: false,
    data: undefined,
    params: {
      userRoleList: []
    }
  }),
  addUserList = (name) => {
    userListDialogData.data = formData.value?.[name] || []
    userListDialogData.params.roleCode = name === 'reAppraisalUsers' ? 'REVIEWER' : 'EXPERT'
    userFieldName.value = name
    userListDialogData.visible = true
  },
  closeUserList = () => {
    userListDialogData.visible = false
  },
  getUserData = (data) => {
    formData.value[userFieldName.value] = data.map(i => {
      return {
        ...i
      }
    })
    closeUserList()
  },
  // 添加项目
  projectListDialogData = reactive({
    visible: false,
    data: undefined
  }),
  addProject = () => {
    projectListDialogData.visible = true
    projectListDialogData.data = formData.value?.projects || []
  },
  closePorject = () => {
    projectListDialogData.visible = false
  },
  getProjectData = (data) => {
    formData.value.projects = data.map(i => {
      return {
        ...i
      }
    })
    closePorject()
  },
  delData = (name, index) => {
    formData.value[name].splice(index, 1)
  },
  // 提交
  comfirm = async (formEl) => {
    if (!formEl) {
      return
    }
    await formEl.validate(async valid => {
      if (valid) {
        const postData = {
          ...formData.value,
          appraisalId: route.query.appraisalId,
          projectCodes: formData.value.projects.map(i => i.projectCode),
          reAppraisalUsers: formData.value.reAppraisalUsers.map(i => i.employeeCode),
          verificationUsers: formData.value.verificationUsers.map(i => i.employeeCode),
          projects: undefined
        }
        await groupSave(postData)
        proxy.$message.success('提交成功')
        dialogVisible.value = false
        formData.value = {}
        reset()
      }
    })
  },
  templateTypeListData = ref(),
  getTemplateTypeList = async () => {
    const res = await templateTypeList()
    templateTypeListData.value = res.data
  }
onMounted(() => {
  getTemplateTypeList()
  getTableData()
})
</script>

<template>
  <el-card class="search mb-16">
    <el-form label-suffix=":" :model="searchForm" size="small">
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item label="分组名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item class="btn">
            <el-button type="primary" @click="search">查询</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card>
    <template #header>
      <div class="flex justify-between">
        <span>列表</span>
        <div>
          <el-button
            type="primary"
            size="small"
            icon="plus"
            @click="addGroup"
          >新建分组</el-button>
        </div>
      </div>
    </template>
    <table-list
      ref="tableListRef"
      :column="column"
      :data="data"
      :pagination="false"
      @get-table-data="getTableData"
    >
      <template #action="{scope}">
        <a @click="addGroup(scope.row,true)">编辑</a>
        <a @click="addGroup(scope.row)">详情</a>
        <a class="text-danger" @click="delGroup(scope.row)">删除</a>
      </template>
    </table-list>
  </el-card>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="59%"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-position="right"
      label-width=""
      label-suffix=":"
    >
      <el-row :gutter="4">
        <el-col :span="12">
          <el-form-item label="分组名称" prop="name">
            <el-input
              v-if="isEdit"
              v-model="formData.name"
              maxlength="50"
              placeholder="请输入"
            />
            <span v-else>{{ formData.name }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="4">
        <el-col :span="24">
          <el-form-item label="评价项目" prop="projects">
            <table-list
              ref="tableListRef"
              :column="column2"
              :pagination="false"
              :data="formData.projects"
              class="w-full"
              :empty-temp="false"
            >
              <template #action="{scope}">
                <a v-if="isEdit" class="text-danger" @click="delData('projects',scope.$index)">删除</a>
              </template>
            </table-list>
            <div>
              <el-button
                v-if="isEdit"
                icon="plus"
                plain
                type="primary"
                class="mt-16"
                size="small"
                @click="addProject"
              >添加项目</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="4">
        <el-col :span="12">
          <el-form-item label="复评人员" prop="reAppraisalUsers">
            <template v-if="formData.reAppraisalUsers?.length">
              <el-tag v-for="(item,index) in formData.reAppraisalUsers" :key="index" class="mr-4 mb-8">{{ item.name }} | {{ item.orgName }} | {{ item.phoneNo }}</el-tag>
            </template>
            <el-button
              v-if="isEdit"
              icon="plus"
              plain
              type="primary"
              size="small"
              @click="addUserList('reAppraisalUsers')"
            >添加复评人员</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="4">
        <el-col :span="12">
          <el-form-item label="核查人员" prop="verificationUsers">
            <template v-if="formData.verificationUsers?.length">
              <el-tag v-for="(item,index) in formData.verificationUsers" :key="index" class="mr-4 mb-8">{{ item.name }} | {{ item.orgName }} | {{ item.phoneNo }}</el-tag>
            </template>
            <el-button
              v-if="isEdit"
              icon="plus"
              plain
              type="primary"
              size="small"
              @click="addUserList('verificationUsers')"
            >添加核查人员</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="核查组长" prop="verifyLeader">
            <el-select v-model="formData.verifyLeader" class="w-full" :disabled="!isEdit">
              <el-option
                v-for="(item,index) in formData.verificationUsers"
                :key="index"
                :value="item.employeeCode"
                :label="`${item.name} | ${item.orgName} | ${item.phoneNo}`"
              >{{ item.name }} | {{ item.orgName }} | {{ item.phoneNo }}</el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button
          type="primary"
          @click="comfirm(formRef)"
        >
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  <user-list-dialog
    :visible="userListDialogData.visible"
    :data="userListDialogData.data"
    :params="userListDialogData.params"
    @close="closeUserList"
    @get-project-data="getUserData"
  />
  <plan-project-dialog
    :visible="projectListDialogData.visible"
    :data="projectListDialogData.data"
    :template-type-list-data="templateTypeListData"
    @close="closePorject"
    @get-project-data="getProjectData"
  />
</template>
