<template>
  <el-dialog :title="`危险化学品列表（${props.title}）`" width="1400px" v-model="dialogVisible" @close="onClose">
    <div class="hazard-header-box">
      <div>
        <el-input placeholder="请输入危险化学品名称" v-model="listQuery.searchName" @clear="pageData" clearable
          style="width: 250px; margin: 0 10px 10px 0" />
        <el-button type="primary" @click="pageData"><el-icon>
            <Search />
          </el-icon>
          查询
        </el-button>
      </div>
      <!-- right -->
      <div>
        <el-button type="primary" @click="onAdd">新增</el-button>
      </div>
    </div>
    <div class="dialog-wrapper-content">
      <el-table :data="tableData" style="width: 100%" highlight-current-row
        :header-cell-style="{ background: '#F6F6F6' }" v-loading="tableLoading" height="100%">
        <el-table-column label="序号" type="index" align="center" width="150" />
        <el-table-column label="企业名称" prop="baOrgName" align="center" width="200"> </el-table-column>
        <el-table-column label="危险化学品名称" prop="cmHazchemName" align="center" width="150"></el-table-column>
        <el-table-column label="最大存储量" prop="cmHazchemStorageMaxQty" align="center" width="120">
          <template #default="{ row }"> {{ row.cmHazchemStorageMaxQty }} {{ row.cmHazchemStorageMaxUnit }} </template>
        </el-table-column>
        <el-table-column label="年使用量" prop="cmHazchemYearUsageQty" align="center" width="120">
          <template #default="{ row }"> {{ row.cmHazchemYearUsageQty }} {{ row.cmHazchemYearUsageUnit }} </template>
        </el-table-column>
        <el-table-column label="是否属于剧毒品" prop="cmHighlyToxicFlag" align="center" width="150">
          <template #default="{ row }">
            {{ row.cmHighlyToxicFlag === 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="是否属于易制毒品" prop="cmEasyMakeToxicFlag" align="center" width="160">
          <template #default="{ row }">
            {{ row.cmEasyMakeToxicFlag === 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="是否属于易制爆品" prop="cmEasyMakeExplosiveFlag" align="center" width="180">
          <template #default="{ row }">
            {{ row.cmEasyMakeExplosiveFlag === 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="是否构成重大危险源" prop="cmMajorHazardFlag" align="center" width="180">
          <template #default="{ row }">
            {{ row.cmMajorHazardFlag === 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="是否属重点监管危险化学名录" prop="cmHazchemListFlag" align="center" width="200">
          <template #default="{ row }">
            {{ row.cmHazchemListFlag === 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="是否属重点监管危险化工工艺" prop="cmHazardProcessFlag" align="center" width="200">
          <template #default="{ row }">
            {{ row.cmHazardProcessFlag === 1 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-link type="primary" @click="onEdit(row)" style="margin-right: 10px">编辑</el-link>
            <el-link type="primary" @click="onView(row)" style="margin-right:10px">查看</el-link>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="onDelete(row)">
              <template #reference>
                <el-link type="danger">删除</el-link>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <MOSTY.Pages :pageConfiger="pageConfiger" @changeNo="changeNo" @changeSize="changeSize">
    </MOSTY.Pages>
  </el-dialog>

  <el-dialog :title="'危险化学品' + honorTitle" width="1200px" v-model="honorDialogVisible" :before-close="closeDialog">
    <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="210px" :model="fromObj" :inline="true"
      :disabled="honorTitle === '查看'" :rules="rules">
      <!-- <el-form-item label="危险化学品名称:" prop="cmHazchemName">
        <el-input v-model="fromObj.cmHazchemName" style="width: 280px" />
      </el-form-item> -->
      <el-form-item label="危险化学品名称:" prop="cmHazchemName">
        <MOSTY.ChemicalNamePicker v-if="honorDialogVisible" v-model="fromObj.cmHazchemName" :width="'280px'" />
      </el-form-item>
      <el-form-item label="危险化学品名称:" prop="cmHazchemName" style="opacity: 0">
        <el-input v-model="fromObj.cmHazchemName" style="width: 280px" />
      </el-form-item>
      <el-form-item label="最大存储量:" prop="cmHazchemStorageMaxQty">
        <el-input-number v-model="fromObj.cmHazchemStorageMaxQty" :min="0" style="width: 280px" />
      </el-form-item>
      <el-form-item label="最大存储量单位:" prop="cmHazchemStorageMaxUnit">
        <el-select v-model="fromObj.cmHazchemStorageMaxUnit" clearable style="width: 280px">
          <el-option label="L" value="L" />
          <el-option label="kg" value="kg" />
        </el-select>
      </el-form-item>
      <el-form-item label="年使用量:" prop="cmHazchemYearUsageQty">
        <!-- <el-input v-model="fromObj.cmHazchemYearUsageQty" style="width: 280px" /> -->
        <el-input-number v-model="fromObj.cmHazchemYearUsageQty" :min="0" style="width: 280px" />
      </el-form-item>
      <el-form-item label="年使用量单位:" prop="mHazchemYearUsageUnit">
        <el-select v-model="fromObj.cmHazchemYearUsageUnit" clearable style="width: 280px">
          <el-option label="L" value="L" />
          <el-option label="kg" value="kg" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否属于剧毒品:" prop="cmHighlyToxicFlag">
        <el-select v-model="fromObj.cmHighlyToxicFlag" placeholder="请选择是否属于剧毒品" style="width: 280px">
          <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否属于易制毒品:" prop="cmEasyMakeToxicFlag">
        <el-select v-model="fromObj.cmEasyMakeToxicFlag" placeholder="是否属于易制毒品" style="width: 280px">
          <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否属于易制爆品:" prop="cmEasyMakeExplosiveFlag">
        <el-select v-model="fromObj.cmEasyMakeExplosiveFlag" placeholder="请选择是否属于易制爆品" style="width: 280px">
          <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否构成重大危险源:" prop="cmMajorHazardFlag">
        <el-select v-model="fromObj.cmMajorHazardFlag" placeholder="请选择是否构成重大危险源" style="width: 280px">
          <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否属重点监管危险化学名录:" prop="cmHazchemListFlag">
        <el-select v-model="fromObj.cmHazchemListFlag" placeholder="请选择是否属重点监管危险化学名录" style="width: 280px">
          <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否属重点监管危险化工工艺:" prop="cmHazardProcessFlag">
        <el-select v-model="fromObj.cmHazardProcessFlag" placeholder="是否属重点监管危险化工工艺" style="width: 280px">
          <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="年份:" prop="yearly">
        <el-date-picker v-model="fromObj.yearly" type="year" placeholder="选择年份" style="width: 280px" value-format="YYYY"> </el-date-picker>
      </el-form-item>
      <el-form-item label="备注:" style="width: 100%">
        <el-input v-model="fromObj.bz" type="textarea" show-word-limit maxlength="200" style="width: 920px" />
      </el-form-item> -->
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="saveForm" v-if="honorTitle !== '查看'">保存</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, watch, nextTick } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import * as MOSTY from "@/components/MyComponents/index";
import * as rule from "@/utils/rules.js";
import { ElMessage } from "element-plus"
const { proxy } = getCurrentInstance()
const props = defineProps({ title: String, query: Object, rowItem: Object })
const { D_BZ_SF } = proxy.$dict("D_BZ_SF")
const dialogVisible = ref(false)
defineExpose({ dialogVisible })
const tableData = ref([])
const tableLoading = ref(false)
const ruleFormRef = ref()
const pageConfiger = reactive({
  pageSize: 10,
  pageCurrent: 1,
  total: 0
})
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 10,
  searchName: ""
})
const emits = defineEmits(["close"]);
const honorTitle = ref("")
const honorDialogVisible = ref(false)
const fromObj = ref({})
const onClose = () => {
  dialogVisible.value = false
  emits("close");
}
const rules = reactive({
  cmHazchemName: [{ required: true, message: "请输入危险化学品名称", trigger: "blur" }],
  // ...rule.znumberRule({ validator: true, require: true }, "cmHazchemStorageMaxQty"),// 最大存储量
  cmHazchemStorageMaxUnit: [{ required: true, message: "请选择最大存储量单位", trigger: "change" }],
  // ...rule.znumberRule({ validator: true, require: true }, "cmHazchemYearUsageQty"), // 年使用量
  ...rule.numbernineRule({ validator: true, require: true, iszs: true, firstNum: 8, lastNum: 4 }, "cmHazchemStorageMaxQty"),
  ...rule.numbernineRule({ validator: true, require: true, iszs: true, firstNum: 8, lastNum: 4 }, "cmHazchemYearUsageQty"),

  cmHazchemYearUsageUnit: [{ required: true, message: "请选择年使用量单位", trigger: "change" }],

  cmHighlyToxicFlag: [{ required: true, message: "请选择是否属于剧毒品", trigger: "change" }],
  cmEasyMakeToxicFlag: [{ required: true, message: "请选择是否属于易制毒品", trigger: "change" }],
  cmEasyMakeExplosiveFlag: [{ required: true, message: "请选择是否属于易制爆品", trigger: "change" }],
  cmMajorHazardFlag: [{ required: true, message: "请选择是否构成重大危险源", trigger: "change" }],
  cmHazchemListFlag: [{ required: true, message: "请选择是否属重点监管危险化学名录", trigger: "change" }],
  cmHazardProcessFlag: [{ required: true, message: "请选择是否属重点监管危险化工工艺", trigger: "change" }],
  // yearly: [{ required: true, message: "请选择年份", trigger: "change" }],
});
const pageData = () => {
  tableLoading.value = true
  tableData.value = []
  let params = {
    orgcode: props.rowItem.orgCode,
    year: props.query.year,
    jd: props.query.jd
  }
  getApi({ ...listQuery, ...params }, "/mosty-jcgl/data/hazardChemicalInfo/chemical/list")
    .then(res => {
      if (res) {
        pageConfiger.total = res.total
        tableData.value = res.records
      }
    })
    .finally(() => {
      tableLoading.value = false
    })
}
/** 清空验证提示 */
const clearValidateErr = () => {
  nextTick(() => {
    if (ruleFormRef.value) ruleFormRef.value.clearValidate()
  })
}
const onAdd = () => {
  honorTitle.value = "新增"
  honorDialogVisible.value = true
  // rowItem
  fromObj.value = {
    orgCode: props.rowItem.orgCode,
    orgName: props.rowItem.orgName,
    // baOrgName: props.rowItem.baOrgName || props.rowItem.orgName
  }
  clearValidateErr()
}
//分页
const changeNo = val => {
  listQuery.pageCurrent = val
  pageData()
}
const changeSize = val => {
  listQuery.pageSize = val
  pageData()
}
const onView = e => {
  honorTitle.value = "查看"
  honorDialogVisible.value = true
  clearValidateErr()
  getApi({ id: e.sourceId }, "/mosty-jcgl/data/hazardChemicalInfo/chemical/detail").then(res => {
    if (res) {
      res.cmHighlyToxicFlag = String(res.cmHighlyToxicFlag || '')
      res.cmEasyMakeToxicFlag = String(res.cmEasyMakeToxicFlag || '')
      res.cmEasyMakeExplosiveFlag = String(res.cmEasyMakeExplosiveFlag || '')
      res.cmMajorHazardFlag = String(res.cmMajorHazardFlag || '')
      res.cmHazchemListFlag = String(res.cmHazchemListFlag || '')
      res.cmHazardProcessFlag = String(res.cmHazardProcessFlag || '')

      fromObj.value = res
    }
  })
}
const onEdit = e => {
  honorTitle.value = "编辑"
  honorDialogVisible.value = true
  clearValidateErr()
  getApi({ id: e.sourceId }, "/mosty-jcgl/data/hazardChemicalInfo/chemical/detail").then(res => {
    if (res) {
      res.cmHighlyToxicFlag = String(res.cmHighlyToxicFlag || '')
      res.cmEasyMakeToxicFlag = String(res.cmEasyMakeToxicFlag || '')
      res.cmEasyMakeExplosiveFlag = String(res.cmEasyMakeExplosiveFlag || '')
      res.cmMajorHazardFlag = String(res.cmMajorHazardFlag || '')
      res.cmHazchemListFlag = String(res.cmHazchemListFlag || '')
      res.cmHazardProcessFlag = String(res.cmHazardProcessFlag || '')

      fromObj.value = res
    }
  })
}
const onDelete = row => {
  getApi({}, `/mosty-jcgl/data/hazardChemicalInfo/chemical/delChemical?id=${row.sourceId}`).then(res => {
    if (res) {
      ElMessage({
        message: "删除成功",
        type: "success"
      })
      pageData()
    }
  })
}
const saveForm = async () => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      // return
      const url = honorTitle.value.includes('新增') ? '/mosty-jcgl/data/hazardChemicalInfo/addChemical' : '/mosty-jcgl/data/hazardChemicalInfo/updateChemical'
      postApi(fromObj.value, url)
        .then(res => {
          proxy.$message.success(`${honorTitle.value.includes('新增') ? '新增' : '编辑'}成功`)
          honorDialogVisible.value = false
          pageData()
        })
        .finally(() => {
          // butLoading.value = false
        })
    }
  })
}

onMounted(() => { })
watch(
  () => dialogVisible.value,
  (n, o) => {
    if (n) {
      pageData()
    }
  },
  { deep: true }
  // { immediate: true, deep: true }
);
const closeDialog = () => {
  if (honorTitle.value !== '查看') {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        honorDialogVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    honorDialogVisible.value = false
  }

};
</script>

<style lang="scss">
.mosty-from-wrap {
  align-items: center;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin: 10px auto;
}

.hazard-header-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
