<template>
  <div class="bigBox">
    <MOSTY.FromPage :title="props.editObj.title" @closeDialog="black">
      <template #content>
        <div class="box_cont">
          <div class="fromBoxs">
            <el-form class="mosty-from-wrap" ref="elform" label-width="150px" :model="formData" :inline="true"
              :rules="rules" :disabled="!props.editObj.saveshow">
              <el-form-item label="风险单元类型:" prop="sitetype">
                <!-- <MOSTY.DictRidioAndSelect :dictData="D_BZ_FXDYLX" v-model="formData.sitetype" style="width: 280px"
                  selectType="radio" disabled placeholder='请选择风险单元类型' /> -->
                <el-input v-model="formData.sitetype" style="width: 280px" disabled></el-input>
              </el-form-item>
              <el-form-item label="风险单元名称:" prop="activityfacility">
                <el-input v-model="formData.activityfacility" style="width: 280px" disabled></el-input>
              </el-form-item>
              <!-- <el-form-item label="风险类型:" prop="type">
                <MOSTY.DictRidioAndSelect :dictData="D_BZ_FXLX" v-model="formData.type" disabled style="width: 280px"
                  selectType="radio" placeholder='请选择风险单元类型' />
              </el-form-item> -->

              <el-form-item label="现有控制措施:" prop="existingMeasures" style="width: 100%">
                <el-input v-model="formData.existingMeasures" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
                  show-word-limit maxlength="500" />
              </el-form-item>
              <el-form-item label="可能存在的风险隐患:" prop="description" style="width: 100%">
                <el-input v-model="formData.description" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
                  show-word-limit maxlength="500" />
              </el-form-item>
              <!-- <el-form-item label="可能产生的后果:" prop="consequense" style="width: 100%">
                <el-select v-model="formData.consequense" multiple placeholder="请选择可能产生的后果">
                  <el-option v-for="item in D_BZ_KNFXHGLX" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item label="可能性(L):" prop="lscore">
                <el-input-number v-model.number="formData.lscore" :min="1" :max="5" :step="1" :precision="0"
                  style="width: 280px"></el-input-number>
              </el-form-item>
              <el-form-item label="严重程度(S):" prop="sscore">
                <el-input-number v-model.number="formData.sscore" disabled :min="1" :max="5" :step="1" :precision="0"
                  style="width: 280px"></el-input-number>
              </el-form-item>
              <!-- <el-form-item label="风险度(R):" prop="RScore">
                <span style="color:#000;display: inline-block;margin:auto ;">{{ formData.lscore && formData.sscore ?
                  (formData.lscore * formData.sscore) : '' }}</span>
              </el-form-item> -->
              <!-- <el-form-item label="检查频率:" prop="jcpl">
                  <MOSTY.DictRidioAndSelect :dictData="D_BZ_JCBZPL" v-model="formData.jcpl" style="width: 280px"
                    selectType="select" placeholder='请选择风险单元类型' />
                </el-form-item> -->
              <el-form-item label="风险等级:" prop="risklevel">
                <MOSTY.DictRidioAndSelect :dictData="D_BZ_FXDJ" v-model="formData.risklevel" disabled
                  style="width: 280px" selectType="select" placeholder='请选择风险单元类型' />
              </el-form-item>
            </el-form>
            <!-- <div>
              <MOSTY.Assort :title="'隐患排查清单'" />
              <div class="btnBox">
                <el-button @click="addkzcs('01')" v-if="props.editObj.saveshow">选择</el-button>
                <el-button @click="addGkcs" v-if="props.editObj.saveshow">新增</el-button>
              </div>
              <section style="height: calc(100vh - 500px);">
                <MOSTY.Table :table-columns="tableColumns" :tableData="tableData" :tableloading="loading"
                  :isSelect="false" :isSort="false" :tableHeight="'100%'">
                  <template #yhLv="{ row }">
                    <dict-tag :options="D_DBZ_YHDJ" :value="row.yhLv" :tag="false"></dict-tag>
                  </template>
                  <template #yhFlag="{ row }">
                    <dict-tag :options="NYHBZ" :value="row.yhFlag" :tag="false"></dict-tag>
                  </template>
                  <template #yhLx="{ row }">
                    <span class="dix-cell">
                      <dict-tag :options="D_BZ_SYPCCJ" :value="row.yhLx" toArr :tag="false" />
                    </span>
                  </template>
                  <template #isPic="{ row }">
                    <dict-tag :options="NSFBXSCTP" :value="row.isPic" :tag="false"></dict-tag>
                  </template>
                  <template #actions="{ row, $index }">
                    <el-popconfirm v-if="props.editObj.saveshow" confirm-button-text="是" cancel-button-text="否"
                      icon-color="red" title="确定要删除?" @confirm="handleDelete(row, $index)">
                      <template #reference>
                        <span class="operdel" size="small">
                          <el-icon>
                            <Delete />
                          </el-icon>
                          删除</span>
                      </template>
                    </el-popconfirm>
                    <span class="operedit" @click="handleEdit(row, $index)">
                      <el-icon>
                        <EditPen />
                      </el-icon>
                      编辑
                    </span>
                  </template>
                </MOSTY.Table>
              </section>
            </div> -->
          </div>
        </div>
      </template>
      <template #footer>

        <el-button @click="saverk(elform)" v-if="props.editObj.showrkbtn">入库</el-button>
        <el-button type="primary" @click="savebmyj(elform)" :loading="loading" v-if="props.editObj.saveshow"><el-icon>
            <DocumentChecked />
          </el-icon>保存</el-button>
        <el-button @click="black"><el-icon>
            <DocumentDelete />
          </el-icon>关闭</el-button>
      </template>
    </MOSTY.FromPage>

    <!-- 控制措施 -->
    <Kzcstab v-if="kzcsshow" v-model="kzcsshow" :defaultData="defaultData" :Single="false" :info='InnerForm'
      :checklibName="checklibName" @confirm="getkzcsData" />

    <InnerDialog v-if="innerShow" :title="`${isKzcsTcEdit ? '编辑' : '新增'}控制措施`" type="fxbskNew" :innerShow="innerShow"
      @changeVi="changeVi" :dict="{ D_DBZ_YHDJ, NSFBXSCTP, NYHBZ }" :formValue="InnerForms" @getList="innerDialogOk" />
  </div>
</template>

<script setup>
import { reactive, ref, watch, getCurrentInstance, onMounted } from "vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { getItem } from "@/utils/storage";
import * as rule from "@/utils/rules.js";
import { isString, getErrMsg } from '@/utils/tools.js';
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import Kzcstab from "../component/kzcstab.vue";
import InnerDialog from "../kzcsk/innerDialog.vue"; // 公用的

const { proxy } = getCurrentInstance();
const { D_BZ_KNFXHGLX, D_BZ_FXLX,
  D_DBZ_YHDJ, NSFBXSCTP, NYHBZ, D_BZ_SYPCCJ, D_BZ_FXDJ
} = proxy.$dict("D_BZ_KNFXHGLX", "D_BZ_FXLX",
  "D_DBZ_YHDJ", "NSFBXSCTP", "NYHBZ", "D_BZ_SYPCCJ", "D_BZ_FXDJ");


const props = defineProps({
  saveBtnShow: {
    type: Boolean,
    default: true
  },
  editObj: {
    type: Object,
    default: () => { }
  }
});
// 新增/编辑- 控制措施form
const InnerForms = ref({
  checklibName: props.editObj?.checklibName,
})
const innerShow = ref(false)
/** 是否 [控制措施]编辑状态 */
const isKzcsTcEdit = ref(false)
/**当前编辑控制措施 索引 -1:新增 索引:编辑 */
const editIndex = ref(-1)

const defaultData = ref([])
const elform = ref();
const InnerForm = ref({})
const tableData = ref([]);
const kzcsshow = ref(false)
const loading = ref(false); //新增保存按钮截流
const lecarr = ref([])
const emits = defineEmits(["close"]);
const parentId = ref()
const checklibName = ref()
const rules = reactive({
  activityfacility: [{ required: true, message: "活动或设施不能为空", trigger: "blur" }],
  sitetype: [{ required: true, message: "风险单元类型不能为空", trigger: "blur" }],
  // consequense: [{ required: true, message: "可能产生的后果不能为空", trigger: "blur" }],
  risklevel: [{ required: true, message: "风险等级不能为空", trigger: "blur" }],
  description: [{ required: true, message: "可能存在的风险隐患不能为空", trigger: "blur" }],
  type: [{ required: true, message: "风险类型不能为空", trigger: "blur" }],
  lscore: [{ required: true, message: "可能性(L)不能为空", trigger: "blur" }],
  sscore: [{ required: true, message: "严重性(S)不能为空", trigger: "blur" }],
  existingMeasures: [{ required: true, message: "现有控制措施不能为空", trigger: "blur" }],
  // jcpl:[{ required: true, message: "检查频率不能为空", trigger: "blur" }]
});
const formData = ref({});
const tableColumns = reactive([
  {
    title: "排查项",
    prop: "checklibName"
  },
  {
    title: "控制措施内容",
    prop: "itemName"
  },
  {
    title: "隐患等级",
    prop: "yhLv",
    slot: true
  },
  {
    title: "隐患说明",
    prop: "yhNote",

  },
  {
    title: "标红项",
    prop: "yhFlag",
    slot: true
  },
  {
    title: "适用排查场景",
    prop: "yhLx",
    slot: true
  },
  {
    title: "是否必须上传图片",
    prop: "isPic",
    slot: true
  },

  {
    title: "操作",
    prop: "actions",
    fixed: 'right',
    slot: true
  }
])

onMounted(() => {
  parentId.value = props.editObj.parentId
  if (props.editObj.id) { xqData(props.editObj.id) }
  // if (props.editObj.sitetype == '20') {
  //   formData.value.sitetype = '02'
  // } else if (props.editObj.sitetype == '30') {
  //   formData.value.sitetype = '03'
  // } else {
  //   formData.value.sitetype = '01'
  // }
  formData.value.sitetype = props.editObj.sitetype
  formData.value.sscore = props.editObj.sscore
  formData.value.activityfacility = props.editObj.activityfacility ? props.editObj.activityfacility : null;
  formData.value.parttype = props.editObj.parttype ? props.editObj.parttype : null;
  formData.value.type = '2'
  InnerForm.value.checklibId = props.editObj.checklibId ? props.editObj.checklibId : null;
  checklibName.value = props.editObj.checklibName ? props.editObj.checklibName : null;
  InnerForm.value.checklibName = checklibName.value;
});
function getRiskLev (riskNum) {
  if (riskNum >= 1 && riskNum <= 7) {
    return 1
  } else if (riskNum >= 8 && riskNum <= 12) {
    return 2
  } else if (riskNum >= 13 && riskNum <= 16) {
    return 3
  } else if (riskNum >= 17 && riskNum <= 25) {
    return 4
  }
  else {
    return 1
  }
}

// 添加排查分类
const addkzcs = (type) => {
  defaultData.value = tableData.value ? tableData.value.map(it => { return it.id }) : []
  kzcsshow.value = true

}
function getkzcsData (val) {
  if (tableData.value.length == 0) {
    tableData.value.push(...val)
  } else {
    tableData.value.push(...val)
    let map = new Map();
    for (let item of tableData.value) {
      map.set(item.id, item);
    }
    tableData.value = [...map.values()];
  }
  formData.value.controlsIds = tableData.value.map(it => { return it.id }).toString()
  kzcsshow.value = false

}
/** 根据左边数,获取需要的风险单位类型
* @param { String } dm 左边数的dm
*/
function getNeedSiteType (dm = '') {
  const siteVal = dm.slice(0, 2)
  if (siteVal == '20') {
    return '02'
  } else if (siteVal == '30') {
    return '03'
  } else {
    return '01'
  }
}
//详情
function xqData (id) {
  getApi({}, `/mosty-jcgl/danger2Baseinfo/getDanger2BaseinfoById/${id}`).then(
    (res) => {
      // res.consequense = res.consequense ? res.consequense.split(",") : [];
      formData.value = res;
      formData.value.type = '2'; // 现状风险
      formData.value.sitetype = formData.value.sitetype || props.editObj.sitetype || '--'
      // formData.value.sitetype = getNeedSiteType(res.sitetype)

      tableData.value = res.list ? res.list : []
    }
  );
}
//
const saverk = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      formData.value.state = "2";
      // 状态 1 = 未入库 2 = 入库, 注意：修改的时候不传入该值，入库的时候必传2，新增的时候随便！
      const params = {
        ...formData.value,
        parentId: parentId.value,
        lscore: formData.value.lscore,
        riskseverity: formData.value.sscore,
        consequense: formData.value.consequense ? formData.value.consequense.toString() : '',
        controls: tableData.value,
      }
      if (formData.value.id) {
        prommit(params, "入库成功");
      } else {
        submit(params, "入库成功");
      }
    } else {
      ElMessage.warning(getErrMsg(fields) || '请输入必填项！！！!')
    }
  });
};



//新增
const savebmyj = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;

      const params = {
        ...formData.value,
        parentId: parentId.value,
        lscore: formData.value.lscore,
        riskseverity: formData.value.sscore,
        consequense: formData.value.consequense ? formData.value.consequense.toString() : '',
        controls: tableData.value,
      }
      if (!formData.value.id) {
        formData.value.state = "1";
        submit(params, "新增成功");
      } else {
        prommit(params, "修改成功");
      }
      loading.value = false;
    } else {
      ElMessage.warning(getErrMsg(fields) || '请输入必填项！！！!')
    }
  });
};
//新增或入库
function submit (data, val) {
  // data.controls = data.controls ? data.controls.toString() : '';
  postApi(data, "/mosty-jcgl/danger2Baseinfo/add").then((res) => {
    ElMessage.success(val);
    emits("close");
  }).finally(() => {
  })
}
//修改或入库
function prommit (data, val) {
  // data.controls = data.controls ? data.controls.toString() : '';
  postApi(data, "/mosty-jcgl/danger2Baseinfo/edit").then((res) => {
    ElMessage.success(val);
    emits("close");
  }).finally(() => {
  })
}
function black (params) {
  if (props.editObj.saveshow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emits("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    emits("close");
  }

}
watch(
  () => [formData.value.lscore, formData.value.sscore],
  ([newlscore, newsscore], [oldlscore, oldsscore]) => {
    // 当 lscore 或 sscore 变化时，调用 getNeedSiteType 方法
    if (newlscore && newsscore) {
      let RScore = newlscore * newsscore; // 计算风险等级
      formData.value.risklevel = getRiskLev(RScore) + '';
    } else {
      formData.value.risklevel = '';
    }
  }
), {
  immediate: true
};
/***新增-管控措施 */
const addGkcs = () => {
  InnerForms.value = {
    checklibName: props.editObj?.checklibName,
  }
  editIndex.value = -1;
  innerShow.value = true; // 显示弹窗
}
const handleEdit = (row, index) => {
  editIndex.value = index;
  InnerForms.value = {
    ...row,
    checklibName: props.editObj?.checklibName,
  }
  innerShow.value = true; // 显示弹窗
}
const handleDelete = (row, index) => {
  tableData.value.splice(index, 1);
}
/**弹窗 状态改变*/
const changeVi = (val) => {
  innerShow.value = val;
};
/**编辑排查项回调弹窗
 * @param { Boolean } val 是否显示
 * @param { Object } formVal 弹窗返回的表单数据
 */
const innerDialogOk = (form1, formVal) => {
  if (editIndex.value > -1) {
    tableData.value[editIndex.value] = formVal
  } else {
    tableData.value.push(formVal);
  }
  innerShow.value = false;
};

</script>

<style lang="scss" scoped>
.fromBoxs {
  padding: 0 9%;
}

.el-form {
  display: flex;
  margin-top: 10px;
  flex-wrap: wrap;
  justify-content: space-between;
}

.el-form-item {
  text-align: center;
}

.fxdjspan {
  display: inline-block;
  width: 100%;
  padding-top: 3px;
  padding-bottom: 3px;
  padding-left: 5px;
  border-radius: 5px;
  color: #fff !important;
}

.blac {
  background-color: #fff;
  border: 1px solid #cbc9c9;
}

.reds {
  background-color: #e80000;
}

.orgs {
  background-color: #ff8040;
}

.blus {
  background-color: #e2d101;
}

.gres {
  background-color: #0080ff;
}

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>
