<template>
  <el-dialog :title="props.title" width="1200px" v-model="dialogVisible" :before-close="onClose">
    <el-form :model="info" :rules="rules" label-suffix=":" :disabled="props.title.includes('详情')" ref="ruleFormRef"
      style="width: 100% !important;">
      <el-row>
        <el-col :span="12">
          <el-form-item label="统计周期">
            <el-select v-model="period" clearable placeholder="请选择" disabled style="width: 300px;">
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <MOSTY.Assort title="安全设施费用" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="年度预算(万元)" prop="safetyFacilitieYearBudget">
            <el-input-number v-model="info.safetyFacilitieYearBudget" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已投入执行" prop="safetyFacilitieInputCost"
            :rules="[{ validator: validatorzx('投入金额', '对应年度预算金额', info.safetyFacilitieYearBudget), required: true, trigger: 'blur' }]">
            <el-input-number v-model="info.safetyFacilitieInputCost" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
      </el-row>
      <MOSTY.Assort title="应急救援费用" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="年度预算(万元)" prop="emergencyRescueYearBudget">
            <el-input-number v-model="info.emergencyRescueYearBudget" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已投入执行" prop="emergencyRescueInputCost"
            :rules="[{ validator: validatorzx('投入金额', '对应年度预算金额', info.emergencyRescueYearBudget), required: true, trigger: 'blur' }]">
            <el-input-number v-model="info.emergencyRescueInputCost" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
      </el-row>
      <MOSTY.Assort title="安全防护用品费用" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="年度预算(万元)" prop="safetyProtectionYearBudget">
            <el-input-number v-model="info.safetyProtectionYearBudget" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已投入执行" prop="safetyProtectionInputCost"
            :rules="[{ validator: validatorzx('投入金额', '对应年度预算金额', info.safetyProtectionYearBudget), required: true, trigger: 'blur' }]">
            <el-input-number v-model="info.safetyProtectionInputCost" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
      </el-row>
      <MOSTY.Assort title="安全信息化费用" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="年度预算(万元)" prop="safetyInformationizeYearBudget">
            <el-input-number v-model="info.safetyInformationizeYearBudget" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已投入执行" prop="safetyInformationizeInputCost"
            :rules="[{ validator: validatorzx('投入金额', '对应年度预算金额', info.safetyInformationizeYearBudget), required: true, trigger: 'blur' }]">
            <el-input-number v-model="info.safetyInformationizeInputCost" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
      </el-row>
      <MOSTY.Assort title="安全生产宣传教育培训支出费用" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="年度预算(万元)" prop="safeProductEduTrainExpenditureYearBudget">
            <el-input-number v-model="info.safeProductEduTrainExpenditureYearBudget" :precision="4"
              style="width: 300px;" :min="minNum" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已投入执行" prop="safeProductEduTrainExpenditureCost"
            :rules="[{ validator: validatorzx('投入金额', '对应年度预算金额', info.safeProductEduTrainExpenditureYearBudget), required: true, trigger: 'blur' }]">
            <el-input-number v-model="info.safeProductEduTrainExpenditureCost" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
      </el-row>
      <MOSTY.Assort title="隐患奖励费用" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="年度预算(万元)" prop="hdRewardYearBudget">
            <el-input-number v-model="info.hdRewardYearBudget" :precision="4" style="width: 300px;" :min="minNum" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已投入执行" prop="hdRewardInputCost"
            :rules="[{ validator: validatorzx('投入金额', '对应年度预算金额', info.hdRewardYearBudget), required: true, trigger: 'blur' }]">
            <el-input-number v-model="info.hdRewardInputCost" :precision="4" style="width: 300px;" :min="minNum" />
          </el-form-item>
        </el-col>
      </el-row>
      <MOSTY.Assort title="安全保险费用" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="年度预算(万元)" prop="safetyInsuranceYearBudget">
            <el-input-number v-model="info.safetyInsuranceYearBudget" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已投入执行" prop="safetyInsuranceInputCost"
            :rules="[{ validator: validatorzx('投入金额', '对应年度预算金额', info.safetyInsuranceYearBudget), required: true, trigger: 'blur' }]">
            <el-input-number v-model="info.safetyInsuranceInputCost" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
      </el-row>
      <MOSTY.Assort title="安全咨询服务器费用" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="年度预算(万元)" prop="safetyConsultingServiceYearBudget">
            <el-input-number v-model="info.safetyConsultingServiceYearBudget" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已投入执行" prop="safetyConsultingServiceInputCost"
            :rules="[{ validator: validatorzx('投入金额', '对应年度预算金额', info.safetyConsultingServiceYearBudget), required: true, trigger: 'blur' }]">
            <el-input-number v-model="info.safetyConsultingServiceInputCost" :precision="4" style="width: 300px;"
              :min="minNum" />
          </el-form-item>
        </el-col>
      </el-row>
      <MOSTY.Assort title="其他费用" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="年度预算(万元)" prop="otherYearBudget">
            <el-input-number v-model="info.otherYearBudget" :precision="4" style="width: 300px;" :min="minNum" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已投入执行" prop="otherInputCost"
            :rules="[{ validator: validatorzx('投入金额', '对应年度预算金额', info.otherYearBudget), required: true, trigger: 'blur' }]">
            <el-input-number v-model="info.otherInputCost" :precision="4" style="width: 300px;" :min="minNum" />
          </el-form-item>
        </el-col>
      </el-row>
      <MOSTY.Assort title="合计总费用数" />
      <el-row>
        <el-col :span="12">
          <el-form-item label="年度预算(万元)">
            <el-input v-model="yearTotal" style="width: 300px;" :min="0" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已投入执行">
            <el-input v-model="executeTotal" style="width: 300px;" :min="0" readonly />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">

        <el-button type="primary" v-loading="loadingShow" @click="onSave(ruleFormRef)"
          v-if="props.title.includes('编辑')"> <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span> </el-button>
        <el-button @click="onClose"> <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span></el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, computed } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
const { proxy } = getCurrentInstance();
const props = defineProps({ title: String, currId: String, id: String });
const emits = defineEmits(["close"]);
const dialogVisible = ref(true);
const loadingShow = ref(false)
const minNum = ref(0)
const ruleFormRef = ref(null)
const info = ref({})
const period = ref(new Date().getFullYear())
const rules = ref({
  ...rule.numbernineRule({ validator: true, require: true, iszs: true }, "safetyFacilitieYearBudget"),
  ...rule.numbernineRule({ validator: true, require: true, iszs: true }, "emergencyRescueYearBudget"),
  ...rule.numbernineRule({ validator: true, require: true, iszs: true }, "safetyProtectionYearBudget"),
  ...rule.numbernineRule({ validator: true, require: true, iszs: true }, "safetyInformationizeYearBudget"),
  ...rule.numbernineRule({ validator: true, require: true, iszs: true }, "safeProductEduTrainExpenditureCost"),
  ...rule.numbernineRule({ validator: true, require: true, iszs: true }, "hdRewardYearBudget"),
  ...rule.numbernineRule({ validator: true, require: true, iszs: true }, "safetyInsuranceYearBudget"),
  ...rule.numbernineRule({ validator: true, require: true, iszs: true }, "safetyConsultingServiceYearBudget"),
  ...rule.numbernineRule({ validator: true, require: true, iszs: true }, "otherYearBudget"),
});
const onClose = () => {
  if(!ruleFormRef.value) return
  if (props.title.includes('编辑')) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        ruleFormRef.value.clearValidate();
        emits('close')
      })
      .catch(() => {
        // catch error
      })
  } else {
    ruleFormRef.value.clearValidate();
    emits('close')
  }

};
function validatorzx(lable, lable2, cost) {
  return (rule, value, callback) => {
    if (!value && value != 0) {
      callback(new Error(`${lable}不能为空`));
    } else if (value > cost) {
      callback(new Error(`${lable}必须小于${lable2}`));
    } else if (value < 0 || !/^[0-9]{0,9}(\.[0-9]{0,4})?$/.test(value)) {
      callback(new Error(`最多输入9位整数，4位小数`));
    } else {
      callback();
    }
  }
}
// 年度预算相加总数
const yearTotal = computed(() => {
  let count = 0
  let { safetyFacilitieYearBudget,
    emergencyRescueYearBudget,
    safetyProtectionYearBudget,
    safetyInformationizeYearBudget,
    safeProductEduTrainExpenditureYearBudget,
    hdRewardYearBudget,
    safetyInsuranceYearBudget,
    safetyConsultingServiceYearBudget,
    otherYearBudget
  } = info.value
  add(safetyFacilitieYearBudget,
    emergencyRescueYearBudget,
    safetyProtectionYearBudget,
    safetyInformationizeYearBudget,
    safeProductEduTrainExpenditureYearBudget,
    hdRewardYearBudget,
    safetyInsuranceYearBudget,
    safetyConsultingServiceYearBudget,
    otherYearBudget
  )
  function add(...args) {
    for (let i = 0; i < args.length; i++) {
      if (isNaN(args[i])) {
        continue;
      } else {
        args[i] = Number(args[i])
        count = args[i] + count
      }
    }
  }
  return Number(count.toPrecision(12)).toFixed(4)
})
// 已投入执行金额
const executeTotal = computed(() => {
  let count = 0
  let { safetyFacilitieInputCost,
    emergencyRescueInputCost,
    safetyProtectionInputCost,
    safetyInformationizeInputCost,
    safeProductEduTrainExpenditureCost,
    hdRewardInputCost,
    safetyInsuranceInputCost,
    safetyConsultingServiceInputCost,
    otherInputCost
  } = info.value
  add(
    safetyFacilitieInputCost,
    emergencyRescueInputCost,
    safetyProtectionInputCost,
    safetyInformationizeInputCost,
    safeProductEduTrainExpenditureCost,
    hdRewardInputCost,
    safetyInsuranceInputCost,
    safetyConsultingServiceInputCost,
    otherInputCost
  )
  function add(...args) {
    for (let i = 0; i < args.length; i++) {
      if (isNaN(args[i])) {
        continue;
      } else {
        args[i] = Number(args[i])
        count = args[i] + count
      }
    }
  }
  return Number(count.toPrecision(12)).toFixed(4)
})
const onSave = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loadingShow.value = true
      let {
        safetyFacilitieInputCost,
        emergencyRescueInputCost,
        safetyProtectionInputCost,
        safetyInformationizeInputCost,
        safeProductEduTrainExpenditureCost,
        hdRewardInputCost,
        safetyInsuranceInputCost,
        safetyConsultingServiceInputCost,
        otherInputCost,
        safetyFacilitieYearBudget,
        emergencyRescueYearBudget,
        safetyProtectionYearBudget,
        safetyInformationizeYearBudget,
        safeProductEduTrainExpenditureYearBudget,
        hdRewardYearBudget,
        safetyInsuranceYearBudget,
        safetyConsultingServiceYearBudget,
        otherYearBudget
      } = info.value
      let _data = {
        sourceId: props.currId,
        reportingYear: period.value,
        safetyFacilitieInputCost: safetyFacilitieInputCost.toString(),
        emergencyRescueInputCost: emergencyRescueInputCost.toString(),
        safetyProtectionInputCost: safetyProtectionInputCost.toString(),
        safetyInformationizeInputCost: safetyInformationizeInputCost.toString(),
        safeProductEduTrainExpenditureCost: safeProductEduTrainExpenditureCost.toString(),
        hdRewardInputCost: hdRewardInputCost.toString(),
        safetyInsuranceInputCost: safetyInsuranceInputCost.toString(),
        safetyConsultingServiceInputCost: safetyConsultingServiceInputCost.toString(),
        otherInputCost: otherInputCost.toString(),
        safetyFacilitieYearBudget: safetyFacilitieYearBudget.toString(),
        emergencyRescueYearBudget: emergencyRescueYearBudget.toString(),
        safetyProtectionYearBudget: safetyProtectionYearBudget.toString(),
        safetyInformationizeYearBudget: safetyInformationizeYearBudget.toString(),
        safeProductEduTrainExpenditureYearBudget: safeProductEduTrainExpenditureYearBudget.toString(),
        hdRewardYearBudget: hdRewardYearBudget.toString(),
        safetyInsuranceYearBudget: safetyInsuranceYearBudget.toString(),
        safetyConsultingServiceYearBudget: safetyConsultingServiceYearBudget.toString(),
        otherYearBudget: otherYearBudget.toString()
      }
      postApi(_data, "/mosty-jcgl/data/Siledger/updateAll").then((res) => {
        ElMessage({
          message: "修改成功",
          type: "success"
        });
        emits("close", true);
      }).finally(() => {
        loadingShow.value = false
      });
    } else {
      ElMessage.warning('请输入必填项！！！')
    };
  })
}
const getDetail = () => {
  let _url = props.id ? "/mosty-jcgl/data/Siledger/getLsjlDetail" : "/mosty-jcgl/data/Siledger/getDetailById"
  let id = props.id ? props.id : props.currId
  getApi({ id }, _url).then((res) => {
    info.value = res
    period.value = res.reportingYear
  })


}
onMounted(() => {
  getDetail()
});
</script>

<style lang="scss" scoped>
.content {
  .topper {
    display: flex;

    .sub-le {
      flex: 1;
      padding: 15px 15px 5px 15px;
      border-right: 1px solid #ebeef5;
    }
  }

  .bottom {
    padding: 0 15px 10px 15px;
  }
}
</style>
