<template>
  <div>
    <MOSTY.PageTree :pageTitle="'排查类型列表'" :isShowLeftTree="false">
      <template #serach>
        <div style="width: 400px;display: flex;margin-bottom: 10px;">
          <el-popconfirm title="确定要同步上级单位检查频率吗？" confirm-button-text="确定" cancel-button-text="取消"
            @confirm="synchronousSuperiorUnitCheckRate">
            <template #reference>
              <el-button v-if="showBt" style="display: flex; justify-content: flex-end;">
                同步上级单位检查频率
              </el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm title="确定要清除本单位全部生产期数据吗？" confirm-button-text="确定" cancel-button-text="取消"
            @confirm="deleteProduction">
            <template #reference>
              <el-button style="display: flex; justify-content: flex-end;">
                清除本单位全部生产期数据
              </el-button>
            </template>
          </el-popconfirm>
        </div>
      </template>
      <template #table>
        <div style='height:calc(100vh - 194px)'>
          <el-table stripe :data="treeData" border row-key="id" :tree-props="{ children: 'children' }"
            style="width: 100%" :height="'100%'" :key="keyCount" v-loading="isLoading">
            <el-table-column prop="zdmc" label="排查类型" show-overflow-tooltip align="left" width="320">
            </el-table-column>
            <el-table-column label="检查频率" show-overflow-tooltip align="center">
              <template #default="{ row }">
                <div style="text-align: center;">
                  <Span v-if="row.hasChild == '1' && row.dm != '200201010000'">/</Span>
                  <dict-tag v-else :options="D_BZ_JCBZPL" :value="row.checkrate" :tag="false"></dict-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="showProduction" label="生产期" show-overflow-tooltip align="left" width="320">
              <template #default="{ row }">
                <div style="text-align: center;">
                  <div>{{ formatDate(row.productionDate[0]) }} - {{ formatDate(row.productionDate[1]) }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="showProduction" label="生产期检查频率" show-overflow-tooltip align="center">
              <template #default="{ row }">
                <div style="text-align: center;">
                  <Span v-if="row.hasChild == '1' && row.dm != '200201010000'">/</Span>
                  <dict-tag v-else :options="D_BZ_JCBZPL" :value="row.productionCheckRate" :tag="false"></dict-tag>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" fixed="right" width="320">
              <template #default="{ row }">
                <div style="text-align: center;">
                  <!-- 灭火器(200201010000)也可以设置 -->
                  <span class="operedit" v-if="!row.children || row.children.length == 0 || row.dm == '200201010000'">
                    <span class="operedit" @click="setFn(row)">
                      <el-icon>
                        <EditPen />
                      </el-icon>设置</span>
                    <span class="operedit" @click="deleteProductionById(row.id)">
                      <el-icon>
                        <Delete />
                      </el-icon>清除生产数据</span>
                  </span>
                  <span v-else>/</span>
                </div>
              </template>
            </el-table-column>
          </el-table>

        </div>
      </template>

    </MOSTY.PageTree>

    <el-dialog v-model="dialogVisible" title="设置排查频率" width="480px" :before-close="handleClose">
      <el-form :model="formQuery" ref="formRef" label-position="top" :rules="rules">
        <el-form-item label="通用检查频率：" :rules="[{ required: true, message: '请选择通用检查频率' }]" prop="checkrate" required>
          <MOSTY.Select v-model="formQuery.checkrate" :options="D_BZ_JCBZPL" clearable placeholder="请选择通用检查频率"
            style="width: 250px">
            <!-- <el-option v-for="item in D_BZ_JCBZPL" :key="item" :label="item.label" :value="item.value" /> -->
          </MOSTY.Select>
        </el-form-item>
        <el-form-item v-if="showProduction" label="生产期：" prop="productionDate">
          <el-date-picker v-model="formQuery.productionDate" type="daterange" range-separator="To"
            start-placeholder="生产期开始日期" end-placeholder="生产期结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item v-if="showProduction" label="生产期检查频率：" prop="productionCheckRate">
          <MOSTY.Select v-model="formQuery.productionCheckRate" :options="D_BZ_JCBZPL" clearable
            placeholder="请选择生产期检查频率" style="width: 250px">
            <!-- <el-option v-for="item in D_BZ_JCBZPL" :key="item" :label="item.label" :value="item.value" /> -->
          </MOSTY.Select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submit" :loading="buttonLoading"> <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>确认</span> </el-button>
          <el-button @click="dialogVisible = false"> <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span></el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, getCurrentInstance, defineEmits, defineProps, watch } from "vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
import dayjs from "dayjs";
const { proxy } = getCurrentInstance();
const emits = defineEmits(["close"]);
const buttonLoading = ref(false);
const isLoading = ref(false); // 是否加载
const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  leftShow: {
    type: Boolean,
    default: true
  },
  Row: {
    type: Object,
    default: {}
  },

  orgids: {
    type: String,
    default: ""
  }
});
// 数据
const { D_BZ_JCBZPL } = proxy.$dict("D_BZ_JCBZPL");
const dialogVisible = ref(false);
const tableloading = ref(false);
const tableData = ref([]);
const formRef = ref(null);
const formQuery = ref({});
// 分页
const listQuery = ref({
  pzlx: 'J',
  id: '10010100',
  level: 2,
  orgids: props.orgids ? props.orgids : null,
  exttype: props.Row.exttype ? props.Row.exttype : null,
});

const total = ref(0);
const rules = reactive({
  region: [{ required: true, message: "请选择通用检查频率", trigger: "blur" }]
});

const showProduction = ref(false);
const showBt = ref(false);
const treeData = ref([]);
// 初始化
onMounted(() => {
  // 基础类  获取现场树
  getTreeData();

});
const getTreeData = () => {
  isLoading.value = true;
  getApi({}, "/mosty-jcgl/checklib/getXcTree").then((res) => {
    console.log('res: ', res);
    treeData.value = res;
    if (res[0].level === '30' || res[0].level === '20' || res[0].level === '10') {
      showProduction.value = true;
    }
    if (res[0].level === '20' || res[0].level === '30') {
      showBt.value = true;
    }
  }).finally(() => {
    isLoading.value = false;
  });;
};

const setFn = (row) => {
  formQuery.value.level = row.level ? row.level : null
  formQuery.value.checklibId = row.dm || row.objChecktypeid
  formQuery.value.checkrate = row.checkrate ? row.checkrate : null
  formQuery.value.productionCheckRate = row.productionCheckRate ? row.productionCheckRate : null
  formQuery.value.productionDate = row.productionDate ? row.productionDate : null
  dialogVisible.value = true;
};
// 关闭弹窗
function handleClose() {
  dialogVisible.value = false;
}

//保存
function submit() {
  formRef.value.validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      postApi(formQuery.value, '/mosty-jcgl/checklib/setCheckRate').then(() => {
        dialogVisible.value = false;
        ElMessage.success("修改成功");

        // 获取现场树
        getTreeData();
      }).finally(() => {
        buttonLoading.value = false;
        formQuery.value = {}
      });
    } else {
      ElMessage.error("请填写完必填项!");
      return false;
    }
  });
}

function formatDate(date) {
  if (!date) return '';
  // return new Date(date).toISOString().slice(0, 10); // 截取前10位
  // 或者使用 dayjs：
  return dayjs(date).format('YYYY-MM-DD');
}

const synchronousSuperiorUnitCheckRate = () => {
  getApi({}, "/mosty-jcgl/checklib/synchronousSuperiorUnitCheckRate").then((res) => {
    getTreeData();
    ElMessage.success("同步成功！");
  })
};

//根据id清除生产期数据
const deleteProductionById = (id) => {
  getApi({ id }, "/mosty-jcgl/checklib/deleteProductionById").then((res) => {
    getTreeData();
  })
};

//清除本单位全部生产期数据
const deleteProduction = () => {
  postApi({}, "/mosty-jcgl/checklib/deleteProduction").then((res) => {
    getTreeData();
    ElMessage.success("清除成功！");
  })
};

</script>

<style lang="scss" scoped>
::v-deep .el-table .cell {
  text-align: left;
}

::v-deep .el-dialog__body {
  height: 13vh !important;
}

.operate {
  color: yellowgreen !important;
}


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

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

.dix-cell {
  display: flex;
  // flex-wrap: wrap;
}

::v-deep .el-form--label-top .el-form-item {
  display: flex;
  align-items: baseline;
}
</style>
