<script setup lang="ts">
defineOptions({
  name: "evaluateChangeManage"
});
import { useRouter } from "vue-router";
import { ref, reactive } from "vue";
import addExam from "./manage/addExam.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import manageObject from "./mould/manageObject.vue";
import dayjs from "dayjs";
import {
  getAssessmentPageList,
  getDelAssessment,
  postCopyAssessment
} from "@/api/manage";
import { assessmentStatus, getStateType } from "@/config/tag";
import { Calendar } from "@element-plus/icons-vue";

const manageObjectRef = ref();
const manageObjectShow = ref(false);
const addExamRef = ref();
const addExamShow = ref(false);
const router = useRouter();

const newAdd = () => {
  addExamRef.value.open();
};
const params = reactive({
  tableData: [],
  params: {
    pageNumber: 1,
    pageSize: 10,
    name: ""
  },
  total: 0
});
const getAssessmentPageListApi = async () => {
  const { code, msg, data } = await getAssessmentPageList(params.params);
  if (code === 200) {
    params.tableData = data.records;
    params.total = data.totalRow;
  } else {
    ElMessage.error(msg);
  }
};
getAssessmentPageListApi();
const handleRowClick = (row: any) => {
  console.log(row);
};
const manageObjectItme = ref({});
const setEdit = (row: any) => {
  // router.push({ path: "/evaluate/children/change/mould/manageObject" });\
  manageObjectShow.value = true;
  Object.assign(manageObjectItme.value, row);
};
// 删除
const setDelete = (row: any) => {
  ElMessageBox.confirm("此操作将永久删除该考核, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const { code, msg } = await getDelAssessment(row.id);
    if (code === 200) {
      getAssessmentPageListApi();
      ElMessage.success("删除成功");
    } else {
      ElMessage.error(msg);
    }
  });
};
const handleCurrentChange = (val: number) => {
  params.params.pageNumber = val;
  getAssessmentPageListApi();
};
const handleSizeChange = (val: number) => {
  params.params.pageSize = val;
  getAssessmentPageListApi();
};
// 复制考核
const dialogVisibleCopy = ref(false);
const copyTitle = ref("");
const copyForm = reactive({
  name: "",
  cycle: "",
  cycleValue: ""
});
const copyFormRules = reactive({
  name: [{ required: true, message: "请输入考核名称", trigger: "blur" }],
  cycle: [{ required: true, message: "请选择考核周期", trigger: "change" }]
});
const copyManage = (row: any) => {
  if (row.cycle) {
    handleRegionChange(row.cycle);
  }
  Object.assign(copyForm, row);
  copyTitle.value = row.name;
  dialogVisibleCopy.value = true;
  copyForm.name = row.name + "_副本";
};
const handleClose = () => {
  dialogVisibleCopy.value = false;
};
const copyFormRef = ref(null);
const saveCopy = () => {
  copyFormRef.value.validate(async valid => {
    if (valid) {
      if (!copyForm.cycleValue) {
        ElMessage.error("请选择考核周期的具体时间");
        return false;
      }
      if (timeType.value == "月度") {
        copyForm.cycleValue = dayjs(new Date(copyForm.cycleValue)).format(
          "YYYY-MM"
        );
      }
      if (timeType.value == "年度") {
        copyForm.cycleValue = dayjs(new Date(copyForm.cycleValue)).format(
          "YYYY"
        );
      }
      if (timeType.value == "日期") {
        copyForm.cycleValue = dayjs(new Date(copyForm.cycleValue)).format(
          "YYYY-MM-DD"
        );
      }
      const { code, msg } = await postCopyAssessment(copyForm);
      if (code === 200) {
        ElMessage.success("复制成功");
        dialogVisibleCopy.value = false;
        getAssessmentPageListApi();
      }
    }
  });
};
const timeType = ref<any>("月度");
const quarterValue = ref(true);
const format = ref<any>("YYYY-MM");
const pickerType = ref<any>("month");
const handleRegionChange = (value: any) => {
  timeType.value = value;
  switch (value) {
    case "年度":
      copyForm.cycleValue = "";
      format.value = "YYYY";
      pickerType.value = "year";
      break;
    case "月度":
      copyForm.cycleValue = "";
      format.value = "YYYY-MM";
      pickerType.value = "month";
      break;
    case "日期":
      copyForm.cycleValue = "";
      format.value = "YYYY-MM-DD";
      pickerType.value = "";
      break;
    case "季度":
      copyForm.cycleValue = "";
      quarterValue.value = true;
      break;
    case "半年":
      copyForm.cycleValue = "";
      quarterValue.value = false;
      break;
  }
};
const yearTime = ref<any>(dayjs(new Date()).format("YYYY"));
const decreaseYear = () => {
  yearTime.value = dayjs().year(yearTime.value).subtract(1, "year").year(); // 减一年
};
const increaseYear = () => {
  yearTime.value = dayjs().year(yearTime.value).add(1, "year").year(); // 加一年
};
const monthOne = item => {
  let start = "";
  let end = "";
  switch (item) {
    case "第一季度":
      start = `${yearTime.value}-01-01`;
      end = `${yearTime.value}-03-31`;
      break;
    case "第二季度":
      start = `${yearTime.value}-04-01`;
      end = `${yearTime.value}-06-30`;
      break;
    case "第三季度":
      start = `${yearTime.value}-07-01`;
      end = `${yearTime.value}-09-30`;
      break;
    case "第四季度":
      start = `${yearTime.value}-10-01`;
      end = `${yearTime.value}-12-31`;
      break;
    case "上半年":
      start = `${yearTime.value}-01-01`;
      end = `${yearTime.value}-06-30`;
      break;
    case "下半年":
      start = `${yearTime.value}-07-01`;
      end = `${yearTime.value}-12-31`;
      break;
  }
  copyForm.cycleValue = `${yearTime.value}年${item}`;
};
</script>

<template>
  <div class="w-[100%]">
    <!-- 发起考核 -->
    <addExam
      ref="addExamRef"
      v-model="addExamShow"
      @addHandClick="getAssessmentPageListApi"
    />
    <manageObject v-if="manageObjectShow" :message="manageObjectItme" />
    <div v-else>
      <div class="mb-2 flex gap-2 justify-between flex-wrap">
        <div class="flex mt-2">
          <div class="flex mr-2">
            <el-input
              v-model="params.params.name"
              style="width: 500px"
              placeholder="搜索考核名称"
              :prefix-icon="Search"
              clearable
              @change="getAssessmentPageListApi"
            />
          </div>
        </div>
        <div class="flex pt-2 mr-6">
          <Auth :value="['发起考核']">
            <el-button type="primary" class="mr-8" @click="newAdd"
              >发起考核</el-button
            >
          </Auth>
        </div>
      </div>
      <div class="mt-8">
        <el-table
          :data="params.tableData"
          style="width: 100%"
          @row-click="handleRowClick"
        >
          <el-table-column prop="name" label="考核名称" width="300" fixed>
            <template #default="{ row }">
              <div @click="setEdit(row)">
                {{ row.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="cycle" label="周期">
            <template #default="{ row }">
              <div @click="setEdit(row)">
                {{ row.cycle }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="cycleValue" label="执行期">
            <template #default="{ row }">
              <div @click="setEdit(row)">
                {{ row.cycleValue }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="assessmentModelNameList"
            label="考核模板"
            width="250"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <div
                v-for="(item, index) in row.assessmentModelNameList"
                :key="index"
                @click="setEdit(row)"
              >
                <!-- {{ JSON.parse(.replace(/'/g, '"') }} -->
                <span v-if="item">{{ item }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="assessmentStatus" label="状态">
            <template #default="{ row }">
              <el-tag
                :type="getStateType(row.assessmentStatus)"
                @click="setEdit(row)"
              >
                {{ assessmentStatus(row.assessmentStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createUser" label="创建人">
            <template #default="{ row }">
              <div @click="setEdit(row)">
                {{ row.createUser }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" sortable>
            <template #default="{ row }">
              <div v-if="row.updateTime">
                {{ dayjs(row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <!-- <el-button link :icon="Edit" /> -->
              <Auth :value="['编辑']">
                <el-dropdown trigger="click">
                  <span class="el-dropdown-link navbar-bg-hover select-none">
                    <el-icon @click="setEdit(row)">
                      <Edit />
                    </el-icon>
                  </span>
                </el-dropdown>
              </Auth>
              <el-dropdown class="ml-2" trigger="click">
                <span class="el-dropdown-link navbar-bg-hover select-none">
                  <el-icon>
                    <More />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu class="setting">
                    <Auth :value="['删除']">
                      <el-dropdown-item @click="setDelete(row)">
                        <el-text type="danger">删除</el-text>
                      </el-dropdown-item>
                    </Auth>
                    <Auth :value="['复制']">
                      <el-dropdown-item @click="copyManage(row)">
                        复制
                      </el-dropdown-item>
                    </Auth>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="flex justify-between item-center">
        <div class="float-left mt-5 ml-2 total">共{{ params.total }}条数据</div>
        <div class="float-right mt-8 mr-8">
          <el-pagination
            v-model:current-page="params.params.pageNumber"
            v-model:page-size="params.params.pageSize"
            background
            layout="prev, pager, next"
            :total="params.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialogVisibleCopy"
      :title="'复制来源：' + copyTitle"
      width="500"
    >
      <el-form
        ref="copyFormRef"
        :model="copyForm"
        :rules="copyFormRules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="copyForm.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="考核周期" prop="cycle">
          <el-radio-group v-model="copyForm.cycle" @change="handleRegionChange">
            <el-radio value="月度" size="large">月度</el-radio>
            <el-radio value="季度" size="large">季度</el-radio>
            <el-radio value="半年" size="large">半年</el-radio>
            <el-radio value="年度" size="large">年度</el-radio>
            <el-radio value="日期" size="large">日期</el-radio>
          </el-radio-group>
          <el-date-picker
            v-if="
              timeType === '月度' || timeType === '日期' || timeType === '年度'
            "
            v-model="copyForm.cycleValue"
            :type="pickerType"
            :format="format"
            placeholder="请选择"
          />
          <el-dropdown
            v-else-if="timeType === '季度' || timeType === '半年'"
            trigger="click"
          >
            <span class="el-dropdown-link navbar-bg-hover select-none">
              <el-input
                v-model="copyForm.cycleValue"
                style="width: 240px"
                placeholder="请选择"
                :prefix-icon="Calendar"
              />
            </span>
            <template #dropdown>
              <el-dropdown-menu class="setting" style="width: 300px">
                <div class="flex justify-between align-center text-base mt-4">
                  <div
                    class="cursor-pointer ml-4 text-xs pt-2"
                    @click="decreaseYear"
                  >
                    <el-icon>
                      <DArrowLeft />
                    </el-icon>
                  </div>
                  <div>{{ yearTime }}</div>
                  <div
                    class="cursor-pointer mr-4 text-xs pt-2"
                    @click="increaseYear"
                  >
                    <el-icon>
                      <DArrowRight />
                    </el-icon>
                  </div>
                </div>
                <div
                  v-if="quarterValue"
                  class="flex justify-center align-center mt-5 mb-5"
                >
                  <el-dropdown-item @click="monthOne('一季度')">
                    一季度
                  </el-dropdown-item>
                  <el-dropdown-item @click="monthOne('二季度')">
                    二季度
                  </el-dropdown-item>
                  <el-dropdown-item @click="monthOne('三季度')">
                    三季度
                  </el-dropdown-item>
                  <el-dropdown-item @click="monthOne('四季度')">
                    四季度
                  </el-dropdown-item>
                </div>
                <div v-else class="flex justify-around align-center mt-5 mb-5">
                  <el-dropdown-item @click="monthOne('上半年')">
                    上半年
                  </el-dropdown-item>
                  <el-dropdown-item @click="monthOne('下半年')">
                    下半年
                  </el-dropdown-item>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveCopy"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
.total {
  font-size: 14px;

  /* font-family: PingFangSC-Regular; */
  font-weight: 400;
  line-height: 22px;
  color: #0009;
  letter-spacing: 0;
}
</style>
