<template>
  <div>
    <el-tabs v-model="curTab">
      <el-tab-pane label="产品审批"
                   name="tab1">
        <info ref="infoRef" />
        <el-form ref="formRef"
                 :model="form"
                 :rules="rules"
                 label-width="100px"
                 label-suffix="："
                 class="form pt-5 mt-5 border-t border-t-solid border-t-[#EDF1F5]"
                 status-icon>
          <el-form-item label="审批意见"
                        prop="status">
            <el-select v-model="form.status"
                       placeholder="请选择">
              <el-option v-for="(item, i) in config[0]?.subject?.itemList.slice(2)"
                         :key="i"
                         :label="item.options"
                         :value="item.itemId" />
            </el-select>
          </el-form-item>
          <el-form-item label="意见描述"
                        prop="opinionDescription">
            <el-input type="textarea"
                      placeholder="审批意见500字以内。"
                      maxlength="500"
                      v-model="form.opinionDescription"></el-input>
          </el-form-item>
          <div class="flex flex-col items-end">
            <div class="mb-[18px] text-sm leading-[1.6]">
              <span class="text-sm font-semibold">审批日期：</span>
              <span>{{ date }}</span>
            </div>
            <div class="inline-flex items-center mb-[18px] text-sm leading-[1.6]">
              <span class="text-sm font-semibold">审批员：</span>
              <span v-if="signed"
                    class="text-lg text-[#f00]">{{ signed }}</span>
              <span v-else
                    class="py-2 px-5 ml-1 text-sm text-white bg-[#006BFF] cursor-pointer"
                    @click="sign">签章</span>
            </div>
          </div>
          <div class="flex justify-end">
            <div class="submit"
                 @click="submit(formRef)">审批</div>
          </div>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import type { TabsPaneContext, FormInstance, FormRules } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import Info from './Info.vue';
import { handleId } from '@/utils/common';
import { findById, examineAndApprove } from '@/api/bank';
import { getTheCurrentUserName, getOperationTime } from '@/api/config';
import { getProcessInformationBasedOnRoles, addOperation } from '@/api/judgment';
import dayjs from 'dayjs';
import Cookies from 'js-cookie';

const emit = defineEmits(['getList']);
interface RuleForm {
  id: any;
  status: any;
  opinionDescription?: string;
}
const router = useRouter();
const route = useRoute();
const projectId = +Cookies.get('sand-projectId');
const levelId = +Cookies.get('sand-level');
const curTab = ref<string>('tab1');
const date = ref<string>(dayjs(new Date()).format('YYYY-M-D'));
const info = ref<any>({});
const config = ref<any[]>([]);
const formRef = ref<FormInstance>();
const infoRef = ref<any>(null);
const form = reactive<RuleForm>({
  id: computed(() => +route.query.id),
  status: '',
  opinionDescription: '',
});
const rules = reactive<FormRules<RuleForm>>({
  status: [{ required: true, message: '请选择审批意见', trigger: 'change' }],
  opinionDescription: [{ required: true, message: '请输入意见描述', trigger: 'blur' }],
});
const signed = ref<string>();

// 配置项
const getConfig = async () => {
  const { process } = await getProcessInformationBasedOnRoles(43); // 专家委员会43
  config.value = process;
};
// 获取操作日期
const getDate = async () => {
  const res = await getOperationTime(levelId, projectId);
  if (res.operationTime) {
    date.value = res.operationTime;
  }
};
// 签章
const sign = async () => {
  const res = await getTheCurrentUserName();
  signed.value = res.userName;
};
// 新增判分记录
const addRecord = async (data: Record<string, any>) => {
  const preIds = `1,${levelId},43`; // 1，关卡id，角色（这个页面是专家委员会审批）
  const approved = !!infoRef.value.info.approvalTime; // 有审批时间则表示审批过了，判分点要用第二次审批的id
  const lcRule = [
    handleId(approved ? 1215 : 145, 69, data.status, preIds + ',' + (approved ? 1215 : 145), 1),
    handleId(approved ? 1216 : 146, 70, data.opinionDescription, preIds + ',' + (approved ? 1216 : 146), 3),
    handleId(approved ? 1217 : 758, 233, signed.value ? 514 : 515, preIds + ',' + (approved ? 1217 : 758), 1),
  ];
  await addOperation({
    checkpointId: levelId,
    parentId: preIds,
    lcJudgmentRuleReq: lcRule,
    projectId,
  });
};
// 提交
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const param = JSON.parse(JSON.stringify(form));
        param.approvalTime = dayjs(new Date()).format('YYYY-M-D');

        await examineAndApprove(param.id, param.opinionDescription, param.status, param.approvalTime);
        addRecord(param);
        ElMessage.success('提交成功！');
        emit('getList', 1);
      } finally {
      }
    }
  });
};
onMounted(() => {
  getConfig();
  getDate();
});
</script>

<style lang="scss" scoped>
@import url(../../../styles/form.scss);
</style>
