<template>
  <el-dialog :title="props.title" width="1200px" v-model="dialogVisible" :before-close="onClose">
    <el-form ref="ruleForms" :model="ruleForm" label-position="right" :rules="rulesData" label-width="180px"
      label-suffix=":" :disabled="props.title.includes('查看')" style="width: 100% !important;">
      <el-row>
        <el-col :span="12">
          <el-form-item label="统计周期" prop="reportingYear">
            <el-select v-model="ruleForm.reportingYear" clearable disabled style="width: 250px;">
              <!-- <el-option v-for="item in ['2024', '2023', '2022']" :key="item" :label="item" :value="item" /> -->
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="title">从业人员人数</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="在册在岗人数" prop="jobDutyPeopleQty">
            <el-input-number v-model="ruleForm.jobDutyPeopleQty" :min="0" style="width: 250px;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="劳务派遣人数" prop="dispatchDutyPeopleQty">
            <el-input-number v-model="ruleForm.dispatchDutyPeopleQty" :min="0" style="width: 250px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="title">安全管理机构</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否独立设置" prop="independentSettingsFlag">
            <el-radio-group v-model="ruleForm.independentSettingsFlag" style="width: 250px;" disabled>
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="编制人数" prop="organizationPeopleQty">
            <el-input-number v-model="ruleForm.organizationPeopleQty" :min="0" style="width: 250px;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配置人数" prop="allocationPeopleQty">
            <el-input-number v-model="ruleForm.allocationPeopleQty" :min="0" style="width: 250px;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否设置安全工程师" prop="sePositionFlag">
            <el-radio-group v-model="ruleForm.sePositionFlag" style="width: 250px;">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设置安全工程师岗位数量" prop="positionQty">
            <el-input-number v-model="ruleForm.positionQty" :min="0" :step="1" :precision="0" style="width: 250px;"
              :disabled="ruleForm.sePositionFlag == 0" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="title">专业持证人数</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="注安人数" prop="safetyPeopleQty">
            <el-input-number v-model="ruleForm.safetyPeopleQty" :min="0" style="width: 250px;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="注消人数" prop="cancellationPeopleQty">
            <el-input-number v-model="ruleForm.cancellationPeopleQty" :min="0" style="width: 250px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="title">安全生产标准化</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="达标级别" prop="complianceLevelCode">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_AQSCBZHDBJB" v-model="ruleForm.complianceLevelCode"
              style="width: 250px;" />
            <!-- <el-radio-group v-model="ruleForm.complianceLevelCode">
              <el-radio :label="1">一级</el-radio>
              <el-radio :label="2">二级</el-radio>
              <el-radio :label="3">三级</el-radio>
              <el-radio :label="4">未评级</el-radio>
            </el-radio-group> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="达标得分" :prop="ruleForm.complianceLevelCode != '4' ? 'complianceScore' : ''">
            <el-input-number v-model="ruleForm.complianceScore" :min="0" :max="100" style="width: 250px;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效截止日期" :prop="ruleForm.complianceLevelCode != '4' ? 'expireDate' : ''">
            <el-date-picker v-model="ruleForm.expireDate" type="date" value-format="YYYY-MM-DD" style="width: 250px;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年度自评得分" :prop="ruleForm.complianceLevelCode != '4' ? 'yearSelfEvaluationScore' : ''">
            <el-input-number v-model="ruleForm.yearSelfEvaluationScore" :min="0" :max="100" style="width: 250px;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="复核结果" prop="reviewResults">
            <MOSTY.DictRidioAndSelect selectType="select" :dictData="reviewResultsOpt" v-model="ruleForm.reviewResults"
              style="width: 250px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="title">职业健康管理体系</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否认证" prop="attestationFlag">
            <el-radio-group v-model="ruleForm.attestationFlag" style="width: 250px;">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效截止日期" :prop="ruleForm.attestationFlag == '0' ? '' : 'effectiveUntilDate'">
            <el-date-picker v-model="ruleForm.effectiveUntilDate" type="date" value-format="YYYY-MM-DD"
              style="width: 250px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="title" style="margin-bottom: 15px">
        单位荣誉情况
        <el-button type="primary" class="fr" v-if="props.title.includes('编辑')" @click="onAdd">新增</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#F6F6F6' }"
        v-loading="tableLoading">
        <el-table-column label="年份" property="year" width="150"></el-table-column>
        <el-table-column label="荣誉/证书名称" property="name" width="250"> </el-table-column>
        <el-table-column label="荣誉获得时间" property="time"></el-table-column>
        <el-table-column label="备注" property="bz"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-link type="primary" @click="clickView(row)">查看</el-link>
            <el-link type="primary" v-if="props.title.includes('编辑')" @click="clickEdit(row)">编辑</el-link>
            <!-- <el-link type="primary" v-if="props.title.includes('编辑')">删除</el-link> -->
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="deldete(row)" v-if="props.title.includes('编辑')">
              <template #reference>
                <el-link type="primary">删除</el-link>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex just-center">
        <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="listQuery.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
          layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">

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

  <el-dialog :title="honorTitle" width="600px" v-model="honorDialogVisible" :before-close="closes">
    <el-form ref="honorRuleRef" :disabled="honorTitle === '查看'" label-width="130px" :model="honorRuleForm"
      :inline="true" label-suffix=":" :rules="honorRules" style="flex-wrap: wrap">
      <el-form-item label="年份" prop="year" style="width: 100%">
        <!-- {{ honorRuleForm.year }} -->
        <el-date-picker style="width: 100%" disabled v-model="honorRuleForm.year" type="year" format="YYYY"
          value-format="YYYY" />
      </el-form-item>
      <el-form-item label="荣誉/证书名称" prop="name" style="width: 100%">
        <el-input v-model="honorRuleForm.name" clearable />
      </el-form-item>
      <el-form-item label="荣誉获得时间" style="width: 100%" prop="time">
        <el-date-picker v-model="honorRuleForm.time" type="date" value-format="YYYY-MM-DD" style="width: 100%" />
      </el-form-item>
      <el-form-item label="备注" style="width: 100%">
        <el-input v-model="honorRuleForm.bz" type="textarea" style="width: 100%; height: 100px" clearable />
      </el-form-item>
      <!-- <el-form-item label="附件" style="width: 100%" prop="fjid">
        <MOSTY.Upload
          :widthNumber="860"
          :limit="20"
          :nopicer="true"
          :isImg="false"
          :ShowfileList="true"
          v-model="honorRuleForm.fjid"
          :showinput="false"
          :key="dialogVisible"
        ></MOSTY.Upload>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="saveForm" v-if="honorTitle !== '查看'">保存</el-button>
        <el-button @click="closes">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, watch, nextTick } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import * as rule from "@/utils/rules.js";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { getItem } from "@/utils/storage";
import { ElMessage } from "element-plus";
const props = defineProps({ title: String, rowItem: Object, id: String });
const { proxy } = getCurrentInstance();
const { D_BZ_AQSCBZHDBJB } = proxy.$dict("D_BZ_AQSCBZHDBJB");
const dialogVisible = ref(false);
const rules = [];
const ruleForm = ref({});
const tableData = ref([]);
const honorDialogVisible = ref(false);
const btnloading = ref(false);
const honorRuleRef = ref();
const reviewResultsOpt = [
  { label: '未复核', value: '未复核' },
  { label: '自评合格', value: '自评合格' },
  { label: '自评基本合格', value: '自评基本合格' },
  { label: '自评不合格', value: '自评不合格' }
]
const honorRuleForm = ref({
  // id:""
  year: "", //new Date().getFullYear().toString(),
  name: "",
  time: "",
  bz: ""
});
const honorRules = reactive({
  // ...rule.percentageRule({ validator: true, require: true }, "score"),
  year: [{ required: true, message: "请选择年份", trigger: "blur", trigger: "change" }],
  name: [{ required: true, message: "请输入荣誉/证书名称", trigger: "blur" }],
  time: [{ required: true, message: "请选择荣誉获得时间", trigger: "change" }],
});
const ruleForms = ref()
const rulesData = ref({
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "jobDutyPeopleQty"),
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "dispatchDutyPeopleQty"),
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "organizationPeopleQty"),
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "allocationPeopleQty"),
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "safetyPeopleQty"),
  ...rule.numberzzsRule({ validator: true, require: true, num: 99999 }, "cancellationPeopleQty"),
  ...rule.percentageRule({ validator: true, require: true }, "complianceScore"),
  ...rule.percentageRule({ validator: true, require: true }, "yearSelfEvaluationScore"),
  independentSettingsFlag: [{ required: true, message: "是否独立设置", trigger: "blur" }],
  sePositionFlag: [{ required: true, message: "是否设置安全工程师岗位", trigger: "blur" }],
  complianceLevelName: [{ required: true, message: "达标级别", trigger: "blur" }],
  expireDate: [{ required: true, message: "有效截止日期", trigger: "blur" }],
  attestationFlag: [{ required: true, message: "是否认证", trigger: "blur" }],
  effectiveUntilDate: [{ required: true, message: "有效截止日期", trigger: "blur" }],
})
const tableLoading = ref(false);
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 5,
  orgid: ''
});
const total = ref(0);
const honorTitle = ref("新增");
const emit = defineEmits(["onSave"]);
defineExpose({ dialogVisible });

const onClose = () => {
  if (props.title.includes('编辑')) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        ruleForms.value.clearValidate();
        dialogVisible.value = false;
      })
      .catch(() => {
        // catch error
      })
  } else {
    ruleForms.value.clearValidate();
    dialogVisible.value = false;
  }

};
function closes() {
  if (honorTitle.value !== '查看') {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        honorDialogVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    honorDialogVisible.value = false
  }

}
const onSave = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      btnloading.value = true
      ruleForm.value.complianceLevelName = D_BZ_AQSCBZHDBJB.value.find((item) => item.value === ruleForm.value.complianceLevelCode).label;
      postApi(ruleForm.value, "/mosty-jcgl/enterpriseInfo/updateAll ")
        .then((res) => {
          ElMessage({
            message: "修改成功",
            type: "success"
          });
          emit("onSave", ruleForm.value);
          ruleForms.value.clearValidate();
          dialogVisible.value = false;
        })
        .finally(() => {
          btnloading.value = false
        });

    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  })

}


const onAdd = () => {
  honorDialogVisible.value = true;
  honorTitle.value = "新增";

  nextTick(() => {
    honorRuleRef.value.clearValidate();
    honorRuleRef.value.resetFields();
  });
};
const clickEdit = (e) => {
  honorDialogVisible.value = true;
  honorTitle.value = "编辑";
  honorRuleForm.value = JSON.parse(JSON.stringify(e));
};
const clickView = (e) => {
  honorDialogVisible.value = true;
  honorTitle.value = "查看";
  honorRuleForm.value = JSON.parse(JSON.stringify(e));
};
const getStandardScore = () => {
  tableLoading.value = true;
  listQuery.orgid = props.rowItem.orgCode
  getApi(listQuery, "/mosty-jcgl/standard/getHonor")
    .then(async (res) => {
      if (res) {
        total.value = res.total;
        tableData.value = res.records;
      }
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

const handleSizeChange = (val) => {
  listQuery.pageSize = val;
  getStandardScore();
};
const handleCurrentChange = (val) => {
  listQuery.pageCurrent = val;
  getStandardScore();
};
const deldete = (e) => {
  postApi({}, `/mosty-jcgl/standard/delHonor/${e.id}`).then((res) => {
    proxy.$message.success("成功");
    getStandardScore();
  });
};
const saveForm = async () => {
  await honorRuleRef.value.validate((valid, fields) => {
    if (valid) {
      let url = "/mosty-jcgl/standard/addHonor"; //新增
      if (honorRuleForm.value.id) url = "/mosty-jcgl/standard/editHonor"; //修改
      honorRuleForm.value.orgid = props.rowItem.orgCode
      honorRuleForm.value.orgname = props.rowItem.baOrgName
      postApi(honorRuleForm.value, url)
        .then((res) => {
          ElMessage({
            message: "修改成功",
            type: "success"
          });
          honorDialogVisible.value = false;
          // if (honorRuleForm.id) {
          //   getStandardScore()
          // } else {
          //   tableData.unshift(res)
          // }
          getStandardScore();
        })
        .finally(() => {
          // butLoading.value = false
        });
    }
  });
};

onMounted(() => {
  // getStandardScore();

});
watch(
  () => dialogVisible.value,
  (n, o) => {
    if (n) {
      let _url = props.id ? '/mosty-jcgl/enterpriseInfo/getLsjlDetail' : "/mosty-jcgl/enterpriseInfo/getDetailById"
      let id = props.id ? props.id : props.rowItem.sourceId
      getApi({ id }, _url).then((res) => {
        if (!res) return;
        honorRuleForm.value.year = res.reportingYear + "";
        if (res.sePositionFlag != 1) res.positionQty = 0 // 没有安全工程师，就没有安全工程师数量
        ruleForm.value = res;
        ruleForm.value.jobDutyPeopleQty = ruleForm.value.jobDutyPeopleQty || 0;
        ruleForm.value.dispatchDutyPeopleQty = ruleForm.value.dispatchDutyPeopleQty || 0;
        ruleForm.value.organizationPeopleQty = ruleForm.value.organizationPeopleQty || 0;
        ruleForm.value.allocationPeopleQty = ruleForm.value.allocationPeopleQty || 0;
        ruleForm.value.safetyPeopleQty = ruleForm.value.safetyPeopleQty || 0;
        ruleForm.value.cancellationPeopleQty = ruleForm.value.cancellationPeopleQty || 0;
        ruleForm.value.complianceScore = ruleForm.value.complianceScore || 0;
        ruleForm.value.yearSelfEvaluationScore = ruleForm.value.yearSelfEvaluationScore || 0;
        if (!ruleForm.value.complianceLevelCode) {
          ruleForm.value.complianceLevelCode = "2";
        } else {
          ruleForm.value.complianceLevelCode += "";
        }
      });

      getStandardScore();
    }
  },
  { deep: true }
  // { immediate: true, deep: true }
);
</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>
