<script setup lang="ts">
defineOptions({
  name: "evaluateChangeManageObject"
});
import { getState, getStateType, assessmentStatus } from "@/config/tag";
import { ref, reactive, onMounted } from "vue";
import {
  getAssessmentQuotaDetails,
  delAssessmentObject,
  getAssessmentObjectDetails,
  postAddAssessmentObject,
  updateAssessmentQuotaDetails
} from "@/api/assessment";
import { getTemplateInfoList } from "@/api/templateInfo";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  treeDept,
  postListTreeWithUserApi,
  postListTree
} from "@/api/department";
import { Search } from "@element-plus/icons-vue";
import messagePerson from "./message.vue";
import dayjs from "dayjs";
// 人员,医疗组,负责人
import {
  postUserList,
  postOrganizationUserPage,
  getLeaderList
} from "@/api/userSetting";
// 获取医疗组的数据
import { postPageGroup } from "@/api/userGroup";
const $props = defineProps({
  message: {
    type: Object
  }
});
const valSelection = ref(false);
const messageData = ref({});
const initParams = reactive({
  params: {
    pageNumber: 1,
    pageSize: 10,
    userName: "",
    modelName: "",
    quotaName: "",
    assessmentId: "",
    orderField: "",
    orderType: ""
  },
  objParams: {
    pageNumber: 1,
    pageSize: 10,
    userName: "",
    modelName: "",
    quotaName: "",
    assessmentId: "",
    orderField: "",
    orderType: ""
  },
  indexParams: {
    pageNumber: 1,
    pageSize: 10,
    userName: "",
    modelName: "",
    quotaName: "",
    assessmentId: "",
    orderField: "",
    orderType: ""
  },
  tmpParams: {
    page: 1,
    pageSize: 100
  },
  total: 0,
  total1: 0,
  list: [],
  Indexlist: [],
  tmpList: []
});
const state = reactive({
  tableType: 0
});

// 转换函数 --- 人员
const convertDepartmentDataRecursive_Person = data => {
  return data.map(department => {
    const { userNameNew, userCodeNew, children } = department;
    return {
      value: userCodeNew,
      label: userNameNew,
      children:
        children.length > 0
          ? children.map(
              child => convertDepartmentDataRecursive_Person([child])[0]
            )
          : []
    };
  });
};
// 转换函数 --- 部门
const convertDepartmentDataRecursive = data => {
  return data.map(department => {
    const { deptCode, deptName, childrenRes } = department;
    return {
      value: deptCode,
      label: deptName,
      children:
        childrenRes.length > 0
          ? childrenRes.map(child => convertDepartmentDataRecursive([child])[0])
          : []
    };
  });
};
const dpetTree = ref([]);
onMounted(() => {
  Object.assign(messageData.value, $props.message);
  switch (messageData.value.assessmentType) {
    case 0:
      initParams.assessmentType = "员工";
      break;
    case 1:
      initParams.assessmentType = "部门";
      break;
    case 2:
      initParams.assessmentType = "医疗组";
      break;
    case 3:
      initParams.assessmentType = "员工";
  }
  assessmentTypeApi(messageData.value.assessmentType);
  initParams.params.assessmentId = $props.message.id;
  initParams.objParams.assessmentId = $props.message.id;
  initParams.indexParams.assessmentId = $props.message.id;
  state.tableType = $props.message.assessmentType;
  getAssessmentQuotaDetailsApi();
  getTemplateInfoListApi();
  getAssessmentObjectDetailsApi();
});
const treeDeptList = ref([]);
const assessmentTypeApi = async value => {
  switch (value) {
    case 0:
      postListTreeWithUserApi();
      break;
    case 1:
      const { data, code } = await postListTree();
      dpetTree.value = convertDepartmentDataRecursive(data);
      break;
    case 2:
      const yiliao = await postPageGroup({
        pageNumber: 1,
        pageSize: 1000
      });
      treeDeptList.value = yiliao.data.records;
      break;
    case 3:
      const fuzhere = await getLeaderList();
      console.log(fuzhere);
      treeDeptList.value = fuzhere.data;
  }
};
// 指标分页查询
const getAssessmentQuotaDetailsApi = async () => {
  const res = await getAssessmentQuotaDetails(initParams.indexParams);
  if (res.code === 200) {
    console.log("指标分页查询", res);
    initParams.Indexlist = res.data.records;
    initParams.total1 = res.data.totalRow;
  }
};
// 考核模板
const getTemplateInfoListApi = async () => {
  const { data, code } = await getTemplateInfoList(initParams.params);
  if (code == 200) {
    initParams.tmpList = data.records;
  }
};
// 删除
const delParams = reactive({
  assessmentId: "",
  objectAddVoList: []
});
// 被考核对象
const addPersonParams = reactive({
  assessmentId: "",
  objectAddVoList: []
});
// 添加被考核人
const value1 = ref();
const delAssessmentObjectApi = async () => {
  if (valSelection.value) {
    ElMessageBox.confirm(
      "该员工考核删除后不可恢复，请谨慎操作！",
      "确定删除该员工考核吗？",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    ).then(async () => {
      const { code, msg } = await delAssessmentObject(delParams);
      if (code === 200) {
        getAssessmentObjectDetailsApi();
        ElMessage.success("删除成功");
      } else {
        ElMessage.error(msg);
      }
    });
  } else {
    ElMessage.warning("请选择要删除的考核对象");
  }
};
// 批量选中
const changeSelection = val => {
  if (val) {
    valSelection.value = true;
    delParams.objectAddVoList = [];
    delParams.assessmentId = messageData.value.id;
    addPersonParams.assessmentId = messageData.value.id;
    let assessmentObjectId;
    let assessmentObjectName;
    val.forEach((item, index) => {
      const obj = {
        assessmentObjectId: item.assessmentObjectId,
        assessmentObjectName: item.assessmentObjectName
      };

      // delParams.objectAddVoList.forEach((item1, index1) => {
      //   if (index == index1) {
      // assessmentObjectId = item.assessmentObjectId;
      // assessmentObjectName = item.assessmentObjectName;
      delParams.objectAddVoList.push(obj);
      //   }
      // });
    });
  }
};
const router = useRouter();
const activeName = ref("first");
// 批量导入
const addsImport = () => {
  router.push({ name: "importIndex", query: { ...messageData.value } });
};
const publishShow = ref(true);
const publish = () => {
  publishShow.value = false;
  ElMessage({
    message: "成功",
    type: "success"
  });
};
// 添加被考核人
const dialogVisibleAdd = ref(false);
const assessmentTypeRef = ref();
const transformArrayFormat = data => {
  return data.assessmentObjectId
    .map((item, index) => {
      return {
        assessmentObjectId: item,
        assessmentObjectName: data.assessmentObjectName[index]
      };
    })
    .flat();
};
// 人员 ---- 部门
const handleRreeSelect = data => {
  const list = ref({});
  const arr = assessmentTypeRef.value.getCheckedNodes().filter(item => {
    return item.children.length == 0;
  });
  list.value.assessmentObjectId = arr.map(item => item.value);
  list.value.assessmentObjectName = arr.map(item => item.label);
  addPersonParams.objectAddVoList = transformArrayFormat(list);
};
// 医疗 --- 医疗主任
const handChange = () => {
  const list = ref({});
  const arr = treeDeptList.value.filter(item => {
    return value1.value.includes(item.groupCode);
  });
  list.value.assessmentObjectId = arr.map(item => item.groupCode);
  list.value.assessmentObjectName = arr.map(item => item.groupName);
  addPersonParams.objectAddVoList = transformArrayFormat(list);
};

const dialogVisibleAddShow = () => {
  dialogVisibleAdd.value = true;
};
// 跳转对应科室
const GoView = row => {
  console.log(row, "路由跳转信息展示", messageData.value);
  const arr = {
    "0": "/draw/children/worker/workerDrak",
    "1": "/draw/children/department/departmentDrank",
    "2": "/draw/children/health/healthDrank",
    "3": "/draw/children/head/headDrank"
  };
  for (let key in arr) {
    if ($props.message.assessmentType == key) {
      router.push({
        path: arr[key],
        query: {
          assessmentId: messageData.value.id,
          assessmentModelId: row.assessmentModelId,
          assessmentObjectId: row.assessmentObjectId,
          assessmentName: row.assessmentModelName,
          assessmentModelName: row.assessmentModelName,
          assessmentName: messageData.value.name,
          assessmentObjectName: row.assessmentObjectName
        }
      });
      return;
    }
  }
};
// 考核对象
const objList = ref([]);
const getAssessmentObjectDetailsApi = async () => {
  const { data, msg, code } = await getAssessmentObjectDetails(
    initParams.objParams
  );
  if (code === 200) {
    objList.value = data.records;
    initParams.total = data.totalRow;
  }
};
const handleSizeChange = (val: number) => {
  initParams.objParams.pageSize = val;
  getAssessmentObjectDetailsApi();
};
const handleCurrentChange = (val: number) => {
  initParams.objParams.pageNumber = val;
  getAssessmentObjectDetailsApi();
};
// 指标
const handleSizeIndexChange = (val: number) => {
  initParams.indexParams.pageSize = val;
  getAssessmentQuotaDetailsApi();
};
const handleCurrentIndexChange = (val: number) => {
  initParams.indexParams.pageNumber = val;
  getAssessmentQuotaDetailsApi();
};
// 指标修改
const updateAssessmentQuotaDetailsApi = async row => {
  const { msg, code } = await updateAssessmentQuotaDetails({
    relationId: row.relationId,
    id: row.id,
    dimId: row.dimId,
    assessmentObjectId: row.assessmentObjectId,
    assessmentModelId: row.assessmentModelId,
    score: row.score,
    finalValue: row.finalValue,
    assessmentId: messageData.value.id
  });
  if (code === 200) {
    ElMessage.success("修改成功");
  } else {
    ElMessage.error(msg);
  }
};
const tableVxeRef = ref();
const editConfig = ref({
  trigger: "click",
  mode: "cell"
});
const editClosedEvent = ({ row, column }) => {
  const $table = tableVxeRef.value;
  if ($table) {
    console.log(111);
    updateAssessmentQuotaDetailsApi(row);
    // Object.assign(indexOf, row);
    // postUpdateApi();
  }
};

// 关闭弹窗
const closePerson = () => {
  Object.assign(addPersonParams, {
    assessmentId: "",
    objectAddVoList: []
  });
  value1.value = [];
  dialogVisibleAdd.value = false;
};

// 添加被考核人
const addPerson = async () => {
  addPersonParams.assessmentId = $props.message.id;
  const { data, msg, code } = await postAddAssessmentObject(addPersonParams);
  if (code === 200) {
    ElMessage.success("添加成功");
    dialogVisibleAdd.value = false;
    getAssessmentObjectDetailsApi();
    closePerson();
  }
};

const changTitle = () => {
  const obj = {
    0: "添加被考核人",
    1: "添加被考核科室",
    2: "添加被考核医疗组",
    3: "添加被考核部门负责人"
  };
  return obj[$props.message.assessmentType];
};
</script>

<template>
  <div class="w-full">
    <div class="w-full flex items-center justify-between">
      <div class="flex items-center justify-between mt-2">
        <div class="bg-icon">
          <div>
            <el-icon>
              <Tickets />
            </el-icon>
          </div>
        </div>
        <div>
          <div class="flex items-center justify-between">
            <h5>{{ messageData.name }}</h5>
            <el-tag :type="getStateType(messageData.assessmentStatus)">
              {{ assessmentStatus(messageData.assessmentStatus) }}
            </el-tag>
          </div>
          <el-text type="info" class="text-xs">
            {{ messageData.cycleValue }}
          </el-text>
        </div>
      </div>
      <div class="mr-10">
        <Auth :value="['公布考核结果']">
          <el-button v-if="publishShow" type="primary" @click="publish"
            >公布考核结果</el-button
          >
        </Auth>
      </div>
    </div>
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="考核对象" name="first">
        <div class="w-full flex items-center justify-between">
          <div class="w-1/2 flex items-center justify-between">
            <el-text class="w-1/5">考核模板</el-text>
            <el-select
              v-model="initParams.objParams.modelName"
              placeholder="请选择"
              filterable
              clearable
              style="width: 250px"
              @change="getAssessmentObjectDetailsApi"
            >
              <el-option
                v-for="itemTmp in initParams.tmpList"
                :key="itemTmp.id"
                :label="itemTmp.tpName"
                :value="itemTmp.tpName"
              />
            </el-select>
            <el-input
              v-model="initParams.objParams.userName"
              class="ml-2"
              clearable
              placeholder="搜索人员"
              :prefix-icon="Search"
              @change="getAssessmentObjectDetailsApi"
            />
          </div>
          <div class="mr-10">
            <!-- <el-button type="primary" plain>批量调整执行人</el-button>
            <el-button type="primary" plain>批量重置流程</el-button> -->
            <Auth :value="['批量删除']">
              <el-button type="primary" plain @click="delAssessmentObjectApi">
                批量删除
              </el-button>
            </Auth>
            <Auth :value="['添加被考核人']">
              <el-button type="primary" plain @click="dialogVisibleAddShow">{{
                changTitle()
              }}</el-button>
            </Auth>
          </div>
        </div>
        <el-table
          :data="objList"
          style="width: 100%"
          @selection-change="changeSelection"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-if="state.tableType == 0 || state.tableType == 3"
            prop="realName"
            label="人员"
            width="100"
          />
          <el-table-column
            v-if="state.tableType == 2"
            prop="assessmentObjectName"
            label="医疗组"
            width="100"
          />
          <el-table-column
            v-if="state.tableType == 0 || state.tableType == 3"
            prop="userName"
            label="工号"
            width="180"
          />
          <el-table-column
            v-if="state.tableType != 2"
            prop="deptName"
            label="科室"
            width="180"
          />
          <el-table-column
            prop="assessmentModelName"
            label="考核模板"
            width="300"
          />
          <el-table-column prop="name" label="更新时间" width="150" sortable>
            <template #default="{ row }">
              {{ dayjs(row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <!-- <el-button link :icon="Edit" /> -->
              <el-icon @click="GoView(row)">
                <View />
              </el-icon>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex justify-between item-center">
          <div class="float-left mt-5 ml-2 total">
            <!-- 共{{ initParams.total }}条数据 -->
          </div>
          <div class="float-right mt-5 mr-8">
            <el-pagination
              v-model:current-page="initParams.objParams.pageNumber"
              v-model:page-size="initParams.objParams.pageSize"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="initParams.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="考核指标" name="second">
        <div class="w-full flex items-center justify-between">
          <div class="w-1/2 flex items-center justify-between">
            <el-text class="w-1/5">考核模板</el-text>
            <el-input
              v-model="initParams.indexParams.userName"
              class="ml-1"
              placeholder="搜索人员"
              @change="getAssessmentQuotaDetailsApi"
            />
            <el-input
              v-model="initParams.indexParams.quotaName"
              class="ml-2"
              placeholder="搜索指标名称"
              :prefix-icon="Search"
              @change="getAssessmentQuotaDetailsApi"
            />
          </div>
          <div class="mr-10">
            <Auth :value="['批量导入指标']">
              <el-button type="primary" plain @click="addsImport"
                >批量导入</el-button
              >
            </Auth>
          </div>
        </div>
        <vxe-table
          ref="tableVxeRef"
          class="mt-3"
          show-overflow
          :edit-config="editConfig"
          :data="initParams.Indexlist"
          @edit-closed="editClosedEvent"
          @selection-change="changeSelection"
        >
          <vxe-column type="checkbox" width="60" />
          <vxe-column field="realName" fixed title="人员" width="100" />
          <vxe-column field="userName" fixed title="工号" width="180" />
          <vxe-column field="deptName" fixed title="部门" width="180" />
          <vxe-column field="name" fixed title="指标名称" width="180" />
          <vxe-column field="scoreRule" fixed title="评价标准" width="180" />
          <vxe-column field="source" fixed title="数据来源" width="180" />
          <vxe-column field="targetValue" fixed title="目标值" width="180" />
          <vxe-column
            field="finalValue"
            fixed
            title="完成值"
            :edit-render="{ name: 'input' }"
            width="180"
          />
          <vxe-column
            field="score"
            fixed
            title="得分"
            :edit-render="{ name: 'input' }"
            width="180"
          />
          <vxe-column field="updateTime" title="更新时间" sortable width="180">
            <template #default="{ row }">
              {{ dayjs(row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
          </vxe-column>
          <vxe-column field="updateTime" title="操作" fixed="right" width="180">
            <template #default> - </template>
          </vxe-column>
        </vxe-table>
        <!-- <el-table :data="initParams.Indexlist" style="width: 100%" max-height="250" @selection-change="changeSelection">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="realName" label="人员" width="100" />
          <el-table-column prop="userName" label="工号" width="180" />
          <el-table-column prop="deptName" label="部门" width="180" />
          <el-table-column prop="name" label="指标名称" width="180" />
          <el-table-column prop="scoreRule" label="评价标准" width="180" />
          <el-table-column prop="source" label="数据来源" width="180" />
          <el-table-column prop="targetValue" label="目标值" width="180" />
          <el-table-column prop="finalValue" label="完成值" width="180" />
          <el-table-column prop="score" label="得分" width="180" />
          <el-table-column prop="updateTime" label="更新时间" width="150" sortable>
          <el-table-column prop="updateTime" label="更新时间" width="150" sortable>
            <template #default="{ row }">
              {{ dayjs(row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default>
              -
            </template>
          </el-table-column>
        </el-table> -->
        <div class="flex justify-between item-center">
          <div class="float-left mt-5 ml-2 total">
            <!-- 共{{ initParams.total1 }}条数据 -->
          </div>
          <div class="float-right mt-5 mr-8">
            <el-pagination
              v-model:current-page="initParams.indexParams.pageNumber"
              v-model:page-size="initParams.indexParams.pageSize"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="initParams.total1"
              @size-change="handleSizeIndexChange"
              @current-change="handleCurrentIndexChange"
            />
          </div>
        </div>
      </el-tab-pane>
      <!-- <el-tab-pane label="统计分析" name="third">
      </el-tab-pane> -->
      <el-tab-pane label="基础信息" name="fourth">
        <!-- 延迟加载获取id -->
        <messagePerson v-if="messageData.id" :id="messageData.id" />
      </el-tab-pane>
    </el-tabs>
    <!-- 添加被考核人 -->
    <el-dialog v-model="dialogVisibleAdd" :title="changTitle()" width="500">
      <div>
        <el-form
          ref="ruleFormRef"
          label-position="top"
          label-width="auto"
          :model="addPersonParams"
        >
          <el-form-item label="" label-position="top">
            <el-tree-select
              v-if="$props.message.assessmentType == 0"
              ref="assessmentTypeRef"
              v-model="value1"
              :data="convertDepartmentDataRecursive_Person(treeDept)"
              multiple
              :render-after-expand="false"
              show-checkbox
              style="width: 240px"
              @check-change="handleRreeSelect"
            />
            <el-tree-select
              v-if="$props.message.assessmentType == 1"
              ref="assessmentTypeRef"
              v-model="value1"
              :data="dpetTree"
              multiple
              :render-after-expand="false"
              show-checkbox
              style="width: 240px"
              @check-change="handleRreeSelect"
            />
            <el-select
              v-if="
                $props.message.assessmentType != 0 &&
                $props.message.assessmentType != 1
              "
              ref="selectRefs"
              v-model="value1"
              multiple
              @change="handChange"
            >
              <el-option
                v-for="(it, id) in treeDeptList"
                :key="id"
                :label="it.groupName"
                :value="it.groupCode"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer w-full flex justify-between mt-4">
          <div>
            <el-button @click="closePerson">取消</el-button>
            <el-button type="primary" @click="addPerson"> 确认 </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.bg-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 45px;
  height: 45px;
  margin-right: 5px;
  background: #00a870;
  border-radius: 5px;

  div {
    // border: 1px solid red;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60%;
    height: 60%;
    color: #00a870;
    background: #fff;
    border-radius: 2px;
  }
}
</style>
