<template>
  <div>
    <el-tabs v-model="curTab"
             @tab-click="tabChange">
      <el-tab-pane label="产品审批"
                   name="tab1">
        <info />
        <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 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, watch, 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 { findById, examineAndApprove } from '@/api/bank';
import { getProcessInformationBasedOnRoles, addOperation } from '@/api/judgment';
import dayjs from 'dayjs';

const emit = defineEmits(['getList']);
interface RuleForm {
  id: any;
  status: any;
  opinionDescription?: string;
}
const router = useRouter();
const route = useRoute();
const curTab = ref<string>('tab1');
const info = ref<any>({});
const config = ref<any[]>([]);
const formRef = ref<FormInstance>();
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' }],
});

// tab切换回调
const tabChange = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};
// 配置项
const getConfig = async () => {
  const { process } = await getProcessInformationBasedOnRoles(43); // 专家委员会43
  config.value = process;
};
watch(
  () => route.query,
  () => {
    // getDetail();
  },
  {
    immediate: true,
  },
);
// 提交
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日');

        // const { message } = await examineAndApprove(param);
        const { message } = await examineAndApprove(param.id, param.opinionDescription, param.status, param.approvalTime);
        // addRecord(param, message);
        ElMessage.success('提交成功！');
        emit('getList', 1);
      } finally {
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
// 新增判分记录
const addRecord = async (data: Record<string, any>, newId: number) => {
  const preIds = `1,2,43,${data.productType ? 45 : 44},${newId}`; // 1，关卡id，角色（这个页面是专家委员会审批），个人/企业（44/45）
  const lcRule = <Record<string, any>[]>[handleId(145, 69, data.status, preIds + ',145', 1), handleId(146, 70, data.opinionDescription, preIds + ',146', 3)];

  await addOperation({
    parentId: preIds,
    lcJudgmentRuleReq: lcRule,
    projectId: 1,
  });
};
onMounted(() => {
  getConfig();
});
</script>

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