<template>
  <div>
    <div class="bigBox" :style="{ height: bigHeight }">
      <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
        <template #content>
          <MOSTY.Assort :title="'基本信息'" />
          <div class="from_box">
            <el-form ref="ruleFormRef" :model="FromData" :rules="rules" label-width="135px" class="demo-ruleForm"
              status-icon :inline="true">
              <el-form-item label="年份：" prop="years">
                <el-date-picker v-model="FromData.years" type="year" format="YYYY" value-format="YYYY"
                  style="width: 337px" />
              </el-form-item>
              <el-form-item label="预算项目：" prop="budgettitle">
                <el-input v-model="FromData.budgettitle" style="width: 337px"></el-input>
              </el-form-item>
              <el-form-item label="财务科目：" prop="cwkm">
                <MOSTY.DictTree :zdbh="'D_TB_YSCWKU'" v-model="FromData.cwkm" :placeholder='"请选择预算类别"'
                  style="width: 337px;" @onChange="caiWuKmChange" />
              </el-form-item>
              <el-form-item label="预算类别：" prop="ctype">
                <MOSTY.Select v-model="FromData.ctype" placeholder="请选择预算类别" style="width: 337px;"
                  :options="yuSuanLbOpts">
                  <!-- <el-option v-for="item in yuSuanLbOpts" :key="item.value" :label="item.label" :value="item.value">
                  </el-option> -->
                </MOSTY.Select>
              </el-form-item>
              <el-form-item label="审批单位：" prop="verifyorgname">
                <el-input v-model="FromData.verifyorgname" style="width: 337px" disabled></el-input>
              </el-form-item>
              <el-form-item label="审批人：" prop="verifyusername">
                <el-input v-model="FromData.verifyusername" style="width: 337px" disabled></el-input>
              </el-form-item>
              <el-form-item label="使用部门:" prop="usedeptid">
                <MOSTY.Department style="width: 337px" :searchType="'04'" placeholder="请选择部门" clearable :deptType="'01'"
                  v-model="FromData.usedeptid" @depitem="handleSelectStatus" :deptId="useFatherDeptid" />
              </el-form-item>
              <el-form-item label="上年使用金额：" prop="lastyearmoney">
                <el-input v-model="FromData.lastyearmoney" type="number" style="width: 337px">
                  <template #append>万元</template> </el-input>
              </el-form-item>
              <el-form-item label="预算金额：" prop="budgetmoney" v-if="!['nzadd'].includes(props.type)">
                <el-input v-model="FromData.budgetmoney" type="number" style="width: 337px">
                  <template #append>万元</template> </el-input>
              </el-form-item>
              <el-form-item label="作业量：" prop="operation">
                <el-input v-model="FromData.operation" type="number" style="width: 337px">
                </el-input>
              </el-form-item>
              <el-form-item label="定额标准：" prop="quotastandard">
                <el-input v-model="FromData.quotastandard" type="number" style="width: 337px">
                </el-input>
              </el-form-item>
              <el-form-item label="年初批复数：" prop="budget" v-if="['nzdetails', 'nzexit', 'nzsh'].includes(props.type)">
                <el-input v-model="FromData.budget" type="number" style="width: 337px">
                  <template #append>万元</template> </el-input>
              </el-form-item>
              <el-form-item label="中期批复数：" prop="tzzj" v-if="['nzadd'].includes(props.type)">
                <el-input v-model="FromData.tzzj" type="number" style="width: 337px">
                  <template #append>万元</template> </el-input>
              </el-form-item>

              <el-form-item label="调整增减数：" prop="tzzj" v-if="['nzdetails', 'nzexit', 'nzsh'].includes(props.type)">
                <el-input v-model="FromData.tzzj" type="number" style="width: 337px">
                  <template #append>万元</template> </el-input>
              </el-form-item>
              <el-form-item label="归口审核增减数：" prop="gkshzj" v-if="['nzsh'].includes(props.type)">
                <el-input v-model="FromData.gkshzj" type="number" style="width: 337px">
                  <template #append>万元</template> </el-input>
              </el-form-item>
              <el-form-item label="批复金额：" prop="budget"
                v-if="(['ncsh'].includes(props.type) || FromData.state == '1') && !['nzexit', 'nzsh', 'nzdetails'].includes(props.type)">
                <el-input v-model="FromData.budget" type="number" style="width: 337px"> <template #append>万元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="预算说明：" style="width: 100%;">
                <el-input v-model="FromData.yssm" style="width: 840px" type="textarea" autosize></el-input>
              </el-form-item>
              <el-form-item label="备注：" style="width: 100%;">
                <el-input v-model="FromData.bz" style="width: 840px" type="textarea" autosize></el-input>
              </el-form-item>
              <el-form-item v-if="['nzadd', 'nzsh', 'ndexit', 'nzdetails'].includes(props.type)" label="调整说明："
                style="width: 100%;">
                <el-input v-model="FromData.tzsm" style="width: 840px;" type="textarea" autosize></el-input>
              </el-form-item>
              <el-form-item label="审批意见：" style="width: 100%;"
                v-if="(['ncsh'].includes(props.type) || (FromData.state == '1' && ['ncdetails'].includes(props.type))) && !['nzexit'].includes(props.type)">
                <el-input v-model="FromData.reviewopinions" style="width: 840px" type="textarea"></el-input>
              </el-form-item>
              <el-form-item label="附件上传：" style="width: 100%;">
                <MOSTY.Upload :widthNumber="840" v-model="FromData.files" :limit="3" :delrow="delrow" :nopicer="true"
                  :showbut="props.saveBtnShow" @filehandleChange="changeFile" :ShowfileList="true" :isImg="false"
                  :showinput="true" :placeholder="'请上传pdf,ofd, doc, docx, xls, xlsx,wps'"
                  :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx', 'wps']" />
              </el-form-item>
            </el-form>
          </div>
          <div v-if="['ncdetails', 'nzdetails', 'ncexit', 'nzexit'].includes(props.type)">
            <MOSTY.Assort :title="'历史记录'" />
            <section style="height: 40vh;">
              <MOSTY.Table :table-columns="tableColumns" :tableData="tableData" :tableloading="tableloading"
                :isSelect="false" :isSort="false" :tableHeight="'100%'" @SortChange="SortChange">
                <template #ctype="{ row }">
                  <dict-tag v-if="row.ctype" :options="D_BZ_YSFYLB" :value="row.ctype" :tag="false" />
                  <span v-else>无</span>
                </template>
                <template #operation="{ row }">
                  {{ row.operation || 0 }}
                </template>
                <template #lastyearmoney="{ row }">
                  {{ row.lastyearmoney || 0 }}
                </template>
                <!-- <template #actions="{ row }">
                  <span  @click="seeInfo(scope.row)">
                    <el-icon>
                      <View />
                    </el-icon>查看</span>
                </template> -->
              </MOSTY.Table>
            </section>
            <div class="fenye">
              <MOSTY.Pages :pageConfiger="pageConfiger" @changeNo="handleCurrentChange"
                @changeSize="handleSizeChange" />
            </div>

          </div>
        </template>
        <template #footer>

          <el-button type="primary" @click="addHander(ruleFormRef)"
            v-if="['ncadd', 'nzadd', 'ncexit', 'nzexit', 'ncsh', 'nzsh',].includes(props.type)">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>{{ showshbtn ? '通过' : '保存' }}</span>
          </el-button>
          <el-button type="primary" @click="CloseEvent">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </template>
      </MOSTY.FromPage>
    </div>
    <!-- 选择参与部门: -->
    <ChooseDept :formInfo="ruleForm" :showDdld="showJkssbm" @closezzjg="closeJhss" @listdata="getSonValue"
      :zzlx="zzlx" />
  </div>
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, defineProps, watch, getCurrentInstance, computed } from "vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import ChooseDept from "@/components/MyComponents/ChooseDept/index.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getItem } from "@/utils/storage";
import { numAdd } from "@/utils/tools.js";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
const { proxy } = getCurrentInstance();
const { D_BZ_YSFYLB } = proxy.$dict("D_BZ_YSFYLB");
const emits = defineEmits(["close", 'resttab']);
const rowid = ref(null)
const addplanShow = ref(false)
const zzlx = ref('')
const showJkssbm = ref(false)
const useFatherDeptid = ref()

/** 可选预算类别对象 */
const dictObj = {
  1: ['2', '9'], // 消防警卫费 -> 应急救援费用,其他
  2: ['5'], // 安全生产教育培训 -> 安全宣传教育费用
  3: ['1'], // 资本性投资 -> 安全设施
  4: ['3'], // 劳动防护 -> 安全防护用品费用
  5: ['4'], // 信息系统建设维护费用-> 安全信息化费用
  6: ['8'], // 中介费、咨询费 -> 安全咨询服务费
  7: ['7'], // 安全生产责任保险投保费用 -> 安全保险
  8: ['6'], // 安全奖励 -> 安全奖励
  9: ['9'], // 安全管理人员薪酬 -> 其他
  10: ['9'], // 其他涉及安全风险分级管控与事故隐患排查治 -> 其他
  11: ['9'], // 三同时安全设施、设施设备支出 -> 其他
  12: ['9'], // 新改扩建项目安全评价投入 -> 其他
}
const yuSuanLbOpts = computed(() => {
  if (!FromData.value.cwkm) return D_BZ_YSFYLB?.value || []
  let valuArr = dictObj[FromData.value.cwkm] || []
  if (!D_BZ_YSFYLB?.value?.length) return []
  let opts = D_BZ_YSFYLB.value.filter(item => {
    return valuArr.includes(item.value)
  })
  return opts
})
//表单数据
const ruleForm = ref({
  orgcode: getItem("deptId").ssdwid,
  orgname: getItem("deptId").ssdwmc,
})
//规则校验
const rules = reactive({
  years: [{ required: true, message: "年份不能为空", trigger: "blur" }],
  budgettitle: [{ required: true, message: "预算项目不能为空", trigger: "blur" }],
  cwkm: [{ required: true, message: "财务科目不能为空", trigger: "blur" }],
  ctype: [{ required: true, message: "预算类别不能为空", trigger: "blur" }],
  ...rule.numbernineRule({ validator: true, require: true, iszs: true, firstNum: 10, lastNum: 4 }, "budgetmoney"),
  verifyorgname: [{ required: true, message: "审批单位不能为空", trigger: "blur" }],
  verifyusername: [{ required: true, message: "审批人不能为空", trigger: "blur" }],
  usedeptid: [{ required: true, message: "请选择时使用部门", trigger: "blur" }],
  ...rule.numbernineRule({ validator: true, require: false, iszs: true, firstNum: 10, lastNum: 4 }, "lastyearmoney"),
  ...rule.numbernineRule({ validator: true, require: false, iszs: true, firstNum: 10, lastNum: 4 }, "operation"),
  ...rule.numbernineRule({ validator: true, require: false, iszs: true, firstNum: 10, lastNum: 4 }, "quotastandard"),
  ...rule.numbernineRule({ validator: true, require: false, iszs: true, firstNum: 10, lastNum: 4 }, "lastyearmoney"),
  ...rule.numbernineRule({ validator: true, require: false, iszs: false, firstNum: 10, lastNum: 4 }, "tzzj"),
  ...rule.numbernineRule({ validator: true, require: false, iszs: false, firstNum: 10, lastNum: 4 }, "gkshzj"),
  budget: [
    {
      validator: (rule, value, callback) => {
        if (!value && value != 0) {
          callback(new Error('请输入年初批复数'));
        } else if (value < 0 && (Number(FromData.value.budgetmoney) + Number(value)) < 0) {
          callback(new Error('批复金额不能比预算金额多'));
        } else if (value > 0 && !/^[0-9]{0,10}(\.[0-9]{0,4})?$/.test(value)) {
          callback(new Error(`只能输入10位整数，4位小数`));
        } else {
          callback();
        }
      },
      trigger: 'blur',
      required: true
    }
  ]
});
const props = defineProps({
  // 判断展示字段
  type: {
    default: 'ncadd',
    type: String
  },
  orgcode: {
    default: '5200520100',
    type: String
  },
  // 标题
  title: {
    default: '',
    type: String
  },
  //id
  id: {
    default: null,
    type: String
  },

  editObj: {
    type: Object,
    default: () => { }
  }
});
const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
const tableColumns = reactive([
  {
    title: "预算项目",
    prop: "budgettitle"
  },
  {
    title: "预算类别",
    prop: "ctype",
    slot: true
  },
  {
    title: "修改时间",
    prop: "xtCjsj"
  },
  {
    title: "作业量",
    prop: "operation",
    slot: true
  },
  {
    title: "预算金额(万元)",
    prop: "budgetmoney"
  },
  {
    title: "去年使用金额(万元)",
    prop: "lastyearmoney",
    slot: true
  },
  {
    title: "剩余金额(万元)",
    prop: "symoney"
  },
  {
    title: "批复金额(万元)",
    prop: "budget"
  },
])
// 数据
const activeNames = ref(["1"]);
const ssdept = getItem("deptId").ssbmid
const ShowfileList = ref(true); //是否展示文件列表
const ruleFormRef = ref();
const orgcode = ref(props.orgcode);
const isdisabled = ref(false)
const showshbtn = ref(false)
const disabled2 = ref(false)
const bigHeight = ref(); //整个高度
const delrow = ref({}); //删除文件列表
const tableloading = ref(false);
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20
});
const tableData = ref([]);
const FromData = ref({
  years: new Date().getFullYear().toString(),
  verifyorgname: '',
  verifyorgid: '',
  verifyusername: '',
  verifyuserid: '',
  files: ''
})
// 初始化
onMounted(() => {
  if (['ncadd', 'nzadd'].includes(props.type)) {
    orgcode.value = props.orgcode ? props.orgcode : ssdept
    shData()
    useFatherDeptid.value = undefined
  }
  if (['ncsh', 'nzexit', 'nzsh'].includes(props.type)) {
    disabled2.value = false

  }
  bigHeightFn();
  activeNames.value = ["1"];
  FromData.value.usedeptname = ssdept.ssbmmc;
  FromData.value.usedeptid = ssdept.ssbmid;
});
//监听当前弹窗类型
watch(
  () => props.type,
  () => {
    isdisabled.value = false
    showshbtn.value = false
    //01-年初添加预算
    //02-年初修改预算  05-中期修改预算
    //03-年初查看详情  04-中期预算详情
    //1-年初审核   2-中期审核
    if (['ncdetails', 'nzdetails'].includes(props.type)) {
      //查看详情
      isdisabled.value = false // 原来是 true
    }
    if (['ncsh', 'nzsh'].includes(props.type)) {
      showshbtn.value = true
    }
    if (['ncdetails', 'nzdetails', 'ncexit', 'nzexit'].includes(props.type)) {
      // 记录类型1为年初2为中期3为年度
      if (['ncdetails', 'ncexit'].includes(props.type)) {
        listQuery.value.jllx = '1'
        getxgjl()
      } else {
        listQuery.value.jllx = '2'
        getxgjl()
      }

    }
  }, { deep: true, immediate: true }
);
//监听当前弹窗类型
watch(
  () => props.id,
  (val) => {
    if (val) {
      getxqData(val)
    } else {
      reset()
    }
  }, { deep: true, immediate: true }
);
function caiWuKmChange() {
  let valuArr = dictObj[FromData.value.cwkm] || []
  FromData.value.ctype = valuArr[0] || '' // 自动选中第一个可用项目
}
function handleSelectStatus(val) {
  FromData.value.usedeptname = val.orgName;
  FromData.value.usedeptid = val.orgCode;
}
const closeJhss = (val) => {
  showJkssbm.value = val;
};
//获取审核人
function shData() {
  // 审批人查询接口换成（安全部门接口中的查询部门负责人接口）
  getApi({ ssdwid: ruleForm.value.orgcode }, '/mosty-jcgl/securitychild/getAqbm').then(Res => {
    if (Res) {
      FromData.value.verifyorgname = Res.ssdwmc
      FromData.value.verifyorgid = Res.ssdwid
      getApi({}, `/mosty-jcgl/securitychild/getFzrByDeptid?deptid=${Res.ssbmid}`).then((res) => {
        FromData.value.verifyusername = res.userName
        FromData.value.verifyuserid = res.id
      })
    }
  })
}
//查询三种类型的修改记录
function getxgjl() {
  listQuery.value.zbid = props.id
  tableloading.value = true;
  postApi(listQuery.value, '/mosty-jcgl/budgets/getJlb').then(res => {
    if (res.orders) {
      tableloading.value = false;
      tableData.value = res.records;
      tableData.value.forEach(async (item) => {
        item.budget = item.budget ? item.budget : 0;
        item.budgetmoney = item.budgetmoney ? item.budgetmoney : 0;
        item.totalcost = item.totalcost ? item.totalcost : 0;
        item.symoney = numAdd("reduce", 2, item.budget, item.totalcost) < 0 ? 0 : numAdd("reduce", 2, item.budget, item.totalcost);
      });
      pageConfiger.total = res.total;
    }
  }).catch((err) => {
    tableData.value = [];
    tableloading.value = false;
  });
}


//记录详情
function seeInfo(row) {
  rowid.value = row.id;
  addplanShow.value = true
}
// 方法
const bigHeightFn = () => {
  bigHeight.value = window.innerHeight - 147 + "px";
};
//清空数据
function reset() {
  FromData.value.files = null
  FromData.value = {};
  FromData.value.years = new Date().getFullYear().toString()
  props.id = null;
  isdisabled.value = false
}
//关闭综合配置表
const CloseEvent = () => {
  if (['ncadd', 'nzadd', 'ncexit', 'nzexit', 'ncsh', 'nzsh',].includes(props.type)) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        reset();
        emits("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    reset();
    emits("close");
  }

};
//保存
const addHander = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (FromData.value) {
        FromData.value.files = FromData.value.files ? FromData.value.files.toString() : null
        if (props.type == 'ncadd') {
          //年初预算审核新增
          getsave(FromData.value)
        }
        if (props.type == 'ncexit') {
          //年初预算审核修改
          getNCupdata(FromData.value)
        }
        if (props.type == 'ncsh') {
          //年初审核
          let params = {
            id: FromData.value.id,
            budget: Number(FromData.value.budget),
            reviewopinions: FromData.value.reviewopinions
          }
          getNcshenh(params)
        }
        if (props.type == 'nzadd') {
          //中期预算审核新增
          getzqsave(FromData.value)
        }
        if (props.type == 'nzsh') {
          //中期预算审核
          FromData.value.gkshzj = Number(FromData.value.gkshzj)
          FromData.value.tzzj = Number(FromData.value.tzzj)

          getZQshenh(FromData.value)
        }
        if (props.type == 'nzexit') {
          //中期预算审核修改
          getZQupdata(FromData.value)
        }
      }
    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  })
}

// 获取排查清单列表数据
const getsave = (val) => {
  postApi(val, "/mosty-jcgl/budgets/ncAdd")
    .then(() => {
      ElMessage.success("新增成功");
      reset();
      emits("close");
      emits("resttab", true);
    })
};
//修改年初预算审核
const getNCupdata = (val) => {
  postApi(val, "/mosty-jcgl/budgets/ncEdit")
    .then(() => {
      ElMessage.success("修改成功");
      reset();
      emits("close");
      emits("resttab", true);
    })
};
//修改中期

const getZQupdata = (val) => {
  postApi(val, "/mosty-jcgl/budgets/zqEdit")
    .then(() => {
      ElMessage.success("修改成功");
      reset();
      emits("close");
      emits("resttab", true);
    })
};

//年初审核预算
const getNcshenh = (val) => {
  postApi(val, "/mosty-jcgl/budgets/ncJudge").then(() => {
    ElMessage.success("审核成功");
    reset();
    emits("close");
    emits("resttab", true);
  })
};
//中期预算新增
function getzqsave(val) {
  postApi(val, "/mosty-jcgl/budgets/zqAdd")
    .then(() => {
      ElMessage.success("新增成功");
      reset();
      emits("close");
      emits("resttab", true);
    })
}
//中期审核预算
const getZQshenh = (val) => {
  postApi(val, "/mosty-jcgl/budgets/zqJudge")
    .then(() => {
      ElMessage.success("审批通过");
      reset();
      emits("close");
      emits("resttab", true);
    })
};

//获取详情
function getxqData(id) {
  getApi({}, `/mosty-jcgl/budgets/getBudgetsById/${id}`).then((res) => {
    res = res ? res : {}
    res.budget = res.budget ? res.budget : 0
    res.gkshzj = res.gkshzj ? res.gkshzj : 0
    res.yeartzzj = res.yeartzzj ? res.yeartzzj : 0
    FromData.value = res
    FromData.value.ncpfs = numAdd("add", 4, res.budget, res.gkshzj);
    orgcode.value = res.departid
    if (props.type == 'ncsh') {
      FromData.value.budget = res.budgetmoney
    }
    if (props.type == 'nzsh') {
      FromData.value.gkshzj = res.tzzj
    }
    useFatherDeptid.value = res.useorgid
    // shData()
    ShowfileList.value = false
  })
}
//分页
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  pageConfiger.pageSize = currentSize;
  getxgjl();
};
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  pageConfiger.pageCurrent = currentPage;
  getxgjl();
};
</script>

<style lang="scss" scoped>
.bigBox {
  display: block;
}


::v-deep .el-collapse {
  padding: 20px !important;
}

.el-form {
  margin: 0 auto;
}

.from_box {
  width: 100%;
  margin: 0 auto;
  color: #000;
}

.demo-ruleForm {
  display: block;
}

.txbj {
  display: flex;
  font-size: #000;
}
</style>
