<script setup>

  import {auditReport} from "@/api/report/flow";
import {submitWarningBusiness} from "@/api/warning/business";
  import feedback from "@/utils/feedback";
  import {listPolice} from "@/api/system/police";
  import {getList,save,delCommon} from '@/api/commonOpinions';
  import useCatchStore from "@/stores/modules/catch";
  import useUserStore from "@/stores/modules/user";
  const userStore = useUserStore();
  const props = defineProps(['dialog','reportId','nextNode','message',"isWarning","isCityAudit","reportProject", 'currentNode', 'auditUnitId', 'flowId'])
  const emits = defineEmits(['submitFeedback',"closeFun"])
  import { getDictValue } from "@/utils/util";
  import { saveLastChoice, loadLastChoice } from '@/utils/lastChoice';

  const catchSotre = useCatchStore();

  const dict = catchSotre.getDicts(["AuditUnitPresetting","ReviewePresetSetting"]);
  const departs = catchSotre.getDeparts() ;
  const formData = ref({
    isAudit:true
  })
  const auditForm= ref()



  //审核人
  const query = ref({
    current: 1,
    departBranch: true
  });
  let polices = ref([])
  function getPoliceList() {
    debugger
    listPolice(query.value).then((data) => {
      polices.value = data.records;
    });
  }


  // 获取常用意见
  const commonList =ref([])
  async function getCommonList(){
    const res =  await  getList();
    commonList.value=res
    if(commonList.value && commonList.value.length > 0 ){
      formData.value.message = commonList.value[0].content
    }
  }
  getCommonList()
  //存为常用
  async function saveCommon(){
    if(formData.value.message){
      const res = await  save({"content":formData.value.message})
       feedback.msgSuccess("保存成功");
      await getCommonList();
    }
  }
  //删除常用
  async function delCommonFun(){
    if(formData.value.message){
      const res = await delCommon({"content":formData.value.message})
      feedback.msgSuccess("保存成功");
      await getCommonList();
    }
  }
  //获取单位为简称
  function getDepartShortName(departData,id,rowName){
    if(departData){
      for(let i =0;i<departData.length;i++){
        let s = departData[i];
        if(s.id === id){
          formData.value[rowName]= s.shortName;
          break;
        }
        if(s.children){
          getDepartShortName(s.children,id,rowName)
        }
      }
    }
  }

  //根据输入值获取信息
  const inputGetList= (val)=>{
    query.value.name = val;
    getPoliceList()
  }

  const closeAdd=()=>{
    formData.value={
      isAudit:true
    }
    emits("closeFun",false)
  }

  const submitFun = async ()=>{
    if (props.auditUnitId && formData.value.approverUnitId !== props.auditUnitId) {
      feedback.msgWarning("办理单位必须与审计单位一致！");
      return;
    }
    debugger
    await auditForm.value.validate();
    await feedback.confirm("是否确认通过？");
    formData.value.reportId = props.reportId;
    //nextNode
    console.log('props.nextNode',props)
    if(props.nextNode){
      formData.value.nextNode = props.nextNode;
    }
    if(props.isWarning){
      formData.value.reportId = props.reportId;
      const res = await submitWarningBusiness(formData.value);
    }else{
      const res = await auditReport(formData.value);
    }

    // === 追加：保存缓存 ===
    try {
      const curUserId = userStore?.user?.userName || userStore?.user?.id || '';
      const nodeKey   = props.currentNode || props.nextNode || 'default';
      saveLastChoice(curUserId, nodeKey, {
        approverUnitId: formData.value.approverUnitId,
        approverUnit:   formData.value.approverUnit,
        approverId:     formData.value.approverId,
        approver:       formData.value.approver,
      });
    } catch (e) {}

    feedback.msgSuccess("操作成功");
    emits('submitFeedback',true)
    closeAdd()
  }

  //获取单位简称
  watch(()=>formData.value.approverUnitId,(val)=>{
    if(props.isWarning && "inform" === props.isWarning){
      return;
    }
    if(val){
      query.value.departId =val;
      getDepartShortName(departs,val,'approverUnit')
    }else{
      delete query.value.departId;
    }
    getPoliceList()
  })
  //获用户名称
  watch(()=>formData.value.approverId,(val)=>{
    debugger
    console.log(polices.value)
    if(props.isWarning && "inform" === props.isWarning){
      return;
    }
    if(val){
      let policesData = polices.value.filter(s=>s.idCode === formData.value.approverId);
      if(policesData.length > 0){
        formData.value.approver = policesData[0].name
      }
    }
  })

  watch(()=>props.reportProject,(val)=>{
    if(val && "inform" === props.isWarning){
      formData.value.approverUnitId=val.projectUnitId;
      formData.value.approverId = val.applicantId;
      formData.value.approverUnit=val.projectUnit;
      formData.value.approver = val.applicant;
      console.log('formData.value',formData.value)
    }
  },{deep:true,immediate:true})


  watch(()=>props.dialog,(val)=>{
    debugger
   if(val){
     const data = catchSotre.getDepartNotPolice()
     const departId = userStore.user.departId;
     let arr =data.filter(s=>s.id == departId);
     if(props.isCityAudit || arr){
       //审核单位
      let approverUnitId = getDictValue(dict.AuditUnitPresetting,departId);
       approverUnitId = approverUnitId?approverUnitId:getDictValue(dict.AuditUnitPresetting,
           "市局审计单位");
       console.log('approverUnitId',approverUnitId)
      //审核人id
      let reviewePreset =getDictValue(dict.ReviewePresetSetting,departId);
       reviewePreset = reviewePreset?reviewePreset:getDictValue(dict.ReviewePresetSetting,
           "编辑报审");
       console.log('reviewePreset',reviewePreset)
       getDepartShortName()
       formData.value.approverId = reviewePreset;
       formData.value.approverUnitId= approverUnitId;
       formData.value.approverUnit = getShortName(departs,approverUnitId)
       query.value.departId =approverUnitId;
       if(props.isWarning && "inform" === props.isWarning){
         delete  query.value.departId;
       }else {
         getPoliceList()
         delete  query.value.departId;
       }
       if (! formData.value.message){
         formData.value.message="请查收"
       }
     }else{


       if( userStore?.user?.departId ){
         formData.value.approverUnit = userStore.user.departName;
         formData.value.approverUnitId= userStore.user.departId;
         query.value.departId =formData.value.approverUnitId;
         console.log('-----------')
         if(props.isWarning && "inform" === props.isWarning){
           delete  query.value.departId;
         }else {
           getPoliceList()
           delete  query.value.departId;
         }

       }
     }
   }
    // === 回显“上次选择”：仅当当前字段为空时才回填 ===
    try {
      const curUserId = userStore?.user?.userName || userStore?.user?.id || '';
      const nodeKey   = props.currentNode || props.nextNode || 'default';

      const hint = loadLastChoice(curUserId, nodeKey);
      if (hint) {
        // 单位
        if (hint.approverUnitId) {
          formData.value.approverUnitId = hint.approverUnitId;
          formData.value.approverUnit   = hint.approverUnit;

          // 如果按单位筛人，触发一次人员加载
          if (props.isWarning !== 'inform') {
            query.value.departId = hint.approverUnitId;
            getPoliceList();
            delete query.value.departId;
          }
        }

        // 审核人
        if ( hint.approverId) {
          formData.value.approverId = hint.approverId;
          formData.value.approver   = hint.approver;
        }
      }
    } catch (e) {}


  })

  watch(
      () => polices.value,
      (list) => {
        if (!formData.value.approverId) return

        const target = list.find(
            s => String(s.idCode) === String(formData.value.approverId)
        )
        if (target) {
          formData.value.approver = target.name
          console.log('polices 加载完成后命中 approver：', target.name)
        }
      },
      { deep: true }
  )

  function getShortName(departData, id) {
    let name = null;
    if (departData) {

      for (let i = 0; i < departData.length; i++) {
        let s = departData[i];
        if (s.id === id) {
          name=  s.shortName;
          break;
        }
        if (s.children) {
          name = getShortName(s.children, id)
          if(name != null){
            break;
          }
        }
      }
    }
    return name;

  }

</script>

<template>
 <el-dialog title="提交审核" v-model="props.dialog" @close="closeAdd">
   <el-form ref="auditForm" :model="formData" :label-width="120">
     <el-form-item v-show="props.isWarning != 'inform'" label="办理单位" prop="approverUnitId" :rules="{ required: true, message: '请选择办理单位', trigger: 'blur' }">
       <depart-tree-select :auth="false" v-model="formData.approverUnitId" :size="'default'" placeholder="" clearable/>
     </el-form-item>
     <el-form-item  v-show="props.isWarning != 'inform'"  label="审核人" prop="approverId" :rules="{ required: true, message: '请选择审核人', trigger: 'blur' }">
       <el-select v-model="formData.approverId" remote :remote-method="inputGetList" filterable>
         <el-option v-for="(item,index) in polices"  :key="index" :value="item.idCode" :label="item.name"></el-option>
       </el-select>
     </el-form-item>
     <el-form-item label="办理意见" prop="message" :rules="{ required: true, message: '请输入办理意见', trigger: 'blur' }">
       <el-input type="textarea" :rows="10"  v-model="formData.message" ></el-input>
     </el-form-item>
     <el-form-item label="常用意见">
       <el-row :gutter="20" style="width:100%">
         <el-col :span="16">
            <el-select  allow-create filterable default-first-option v-model="formData.message">
              <el-option v-for="(item,index) in commonList" :key="index"
                :value="item.content" :label="item.content"
              ></el-option>
            </el-select>
         </el-col>
         <el-col :span="8">
            <el-button type="primary" @click="saveCommon" >存为常用</el-button>
           <el-button  @click="delCommonFun">删除常用</el-button>
         </el-col>
       </el-row>

     </el-form-item>
   </el-form>
   <div class="flex end">
     <el-button  @click="closeAdd">关闭</el-button>
     <el-button type="primary" @click="submitFun">提交</el-button>
   </div>
 </el-dialog>
</template>

<style scoped lang="scss">

</style>
