<!--
 * @Description: 威胁预警
 * @Author: xuch
 * @Date: 2022-08-25 14:19:18
 * @LastEditTime: 2023-08-31 20:52:21
 * @LastEditors: 曹文丽
-->
<script lang="ts" setup>
import { ref, reactive, watch, watchEffect, onMounted, nextTick } from "vue";
import type { TabsPaneContext } from "element-plus";
import { ElMessageBox, ElMessage, FormRules, ElIcon } from "element-plus";
import sechdata from "../../../components/sechdata/index.vue";
import searchForm from "../../../components/sechdata/searchForm.vue";
import ViewDetail from "../components/viewDetail.vue";
import {
  getWarnList,
  getWarnCount,
  getWarnStatusCount,
  addUploadFile,
  getEnterprise,
  addWarning,
  updateWarning,
  issueWarning,
  delWarning,
  getWarnTrend,
} from "../../../api/disposal";
import { usePermissions } from "../../../composables/usePermissions";
import { handleGetIndex } from "../../../utils/tools";
import level_2 from "../../../assets/image/d-icon.png";
import level_1 from "../../../assets/image/m-icon.png";
import level_0 from "../../../assets/image/h-icon.png";
import { getThemeColor } from "../../../components/chart/options/theme";
const yaTheme = localStorage.getItem("YA_THEME");
const { permissionsButtons } = usePermissions();
const butomData = ref([]);
const style = "width:14%";
const uploadRef = ref({});
const currentTab = ref(null);
const tablist = ref([
  {
    value: null,
    img: "./resource/images/allimg.png",
    name: "全部",
    num: 0,
    color: "#0095FF",
  },
  {
    value: 1,
    img: "./resource/images/Created.png",
    name: "已创建",
    num: 0,
    color: "#E65857",
  },
  {
    value: 2,
    img: "./resource/images/Issued.png",
    name: "已下发",
    num: 0,
    color: "#4E9B40",
  },
]);
const formColumn = ref({
  img: "./resource/images/emergencyw.png",
  num: 0,
  title: "预警任务总数（个）",
  bgimg:
    yaTheme === "light"
      ? "./resource/images/emergencyw-bg.png"
      : "./resource/images/emergencyw-bg1.png",
  color: "#1AD7FF",
  newadd: 0,
});

const linedata = ref({
  title: "近7日预警任务趋势",
  series: [
    {
      name: "近7日预警任务趋势",
      type: "line",
      symbolSize: 9,
      data: [],
    },
  ],
  xdata: [],
});
const pieData = ref([]);
// 搜索栏
const serchColumns = reactive([
  {
    key: "warningName",
    type: "input",
    label: "预警名称",
    col: 8,
  },
  {
    key: "enterpriseName",
    type: "input",
    label: "企业名称",
    col: 8,
  },
  {
    key: "level",
    type: "select",
    label: "预警等级",
    options: [
      {
        value: 0,
        label: "高",
      },
      {
        value: 1,
        label: "中",
      },
      {
        value: 2,
        label: "低",
      },
    ],
    col: 8,
  },
  {
    key: "warningStatus",
    type: "select",
    label: "任务状态",
    options: [
      {
        value: 1,
        label: "已创建",
      },
      {
        value: 2,
        label: "已下发",
      },
    ],
    col: 8,
  },
  {
    key: "creatorName",
    type: "input",
    label: "创建人",
    col: 8,
  },
]);

// 搜索数据
const serchformData = reactive({
  warningStatus: null,
});
const page = ref(1);
const total = ref(5);
const pageSize = ref(20);
const tableData = ref([]);

const column: any[] = reactive([
  {
    prop: "warningName",
    label: "预警名称",
    minWidth: "180px",
    fixed: "left",
  },
  {
    prop: "warningDescribe",
    label: "预警描述",
    minWidth: "150px",
    // headerSlotName: 'Link'
  },
  {
    prop: "levelStr",
    label: "预警等级",
    width: "110px",
  },
  {
    prop: "enterpriseName",
    label: "企业名称",
    minWidth: "220px",
  },
  {
    prop: "creatorName",
    label: "创建人",
    width: "130px",
  },
  {
    prop: "createTime",
    label: "创建时间",
    width: "190px",
  },
  {
    prop: "issueTime",
    label: "下发时间",
    width: "190px",
  },
  {
    prop: "warningStatusStr",
    label: "状态",
    width: "120px",
  },
  {
    prop: "oparation",
    label: "操作",
    width: "210px",
    align: "center",
    slotName: "oparation",
    buttons: [
      {
        title: "详情",
        hide: () => {
          if (butomData.value.indexOf("详情") > -1) {
            return true;
          }
        },
        eventName: function (row) {
          viewBtn(row);
        },
      },
      {
        title: "下发",
        hide: (row) => {
          if (butomData.value.indexOf("下发") > -1 && row.warningStatus === 1) {
            return true;
          }
        },
        eventName: function (row) {
          issueBtn(row);
        },
      },
      {
        title: "编辑",
        hide: (row) => {
          if (butomData.value.indexOf("编辑") > -1 && row.warningStatus === 1) {
            return true;
          }
        },
        eventName: function (row) {
          edit(row);
        },
      },
      {
        title: "删除",
        hide: (row) => {
          if (butomData.value.indexOf("删除") > -1 && row.warningStatus === 1) {
            return true;
          }
        },
        eventName: function (row) {
          deletedata(row);
        },
      },
    ],
  },
]);
const rightButtons = ref([]);

onMounted(() => {
  permissionsButtons.map((item) => {
    butomData.value.push(item.label);
  });
  search("loading");
  if (butomData.value.indexOf("新增") > -1) {
    rightButtons.value.push({
      text: "新增",
      type: "primary",
      green: true,
      iconType: "add",
      eventName: function () {
        addData();
      },
    });
  }
});

watch(
  () => serchformData.warningStatus,
  () => {
    if (serchformData.warningStatus === "") {
      serchformData.warningStatus = null;
    }
    currentTab.value = serchformData.warningStatus;
    // search();
  }
);
// 初始化
const init = () => {
  getWarnCount().then((res) => {
    const { code, data = {} } = res || {};
    if (code === 200) {
      formColumn.value.num = data["预警任务总数"];
      formColumn.value.newadd = data["今日新增"];
    }
  });

  getWarnStatusCount().then((res) => {
    const { code, data = {} } = res || {};
    if (code === 200) {
      const { count, percent } = data;
      tablist.value[0].num = count["全部"];
      tablist.value[1].num = count["已创建"];
      // pieData.value.series[1].value = tablist.value[2].num = count["已下发"];
      let createpercent = percent["已创建"];
      let downpercent = percent["已下发"];
      // pieData.value.series[0].per = createpercent;
      // pieData.value.series[1].per = downpercent;
      // pieData.value.series[0].value = createpercent.split("%")[0];
      // pieData.value.series[1].value = downpercent.split("%")[0];
      pieData.value = [
        {
          name: "已创建",
          value: createpercent.split("%")[0],
          percent: createpercent,
        },
        {
          name: "已下发",
          value: downpercent.split("%")[0],
          percent: downpercent,
        },
      ];
    }
  });

  getWarnTrend().then((res) => {
    const { code, data = {} } = res || {};
    if (code === 200) {
      const keys = Object.keys(data);
      const values = Object.values(data);
      linedata.value.series[0].data = values;
      linedata.value.xdata = keys;
    }
  });

  getEnterpriseList();
};

// 重置
const reset = () => {
  Object.assign(serchformData, initFromData());
  search();
};
let initFromData = () => {
  page.value = 1;
  return {};
};
const tableBtnClick = (btn, row) => {
  btn.eventName(row);
};
const sizeChange = function (val: Number) {
  pageSize.value = val;
  page.value = 1;
  search();
};
const currentChange = function (val: Number) {
  page.value = val;
  search();
};
// 获取列表页 demo
const search = (loading?) => {
  let data = JSON.parse(JSON.stringify(serchformData));
  data.pageSize = pageSize.value;
  data.pageNum = page.value;
  data.yaLoading = loading;
  getWarnList(data).then((res) => {
    const { code, data = {} } = res || {};
    if (code === 200) {
      let onlydetailbtn = 0;
      data.rows &&
        data.rows.forEach((item) => {
          if (item.warningStatus !== 1) {
            onlydetailbtn++;
          }
          switch (item.level) {
            case 0:
              item.levelimg = level_0;
              item.levelhtml = `<span style="color: #D90808;">${item.levelStr}</span>`;
              break;
            case 1:
              item.levelimg = level_1;
              item.levelhtml = `<span style="color: #F18301;">${item.levelStr}</span>`;
              break;
            case 2:
              item.levelimg = level_2;
              item.levelhtml = `<span style="color: #0095FF;">${item.levelStr}</span>`;
              break;
          }
        });
      let i = handleGetIndex(column, "prop", "oparation");
      if (onlydetailbtn === data.rows.length) {
        column[i].width = "80px";
      } else {
        column[i].width = "210px";
      }
      tableData.value = data.rows;
      total.value = data.total;
    }
  });
  init();
};

// tab页切换
const handleChangeTab = (i) => {
  serchformData.warningStatus = i;
  search();
};

// 按钮相关事件开始
const enterpriseList = ref([]);
let formData = reactive({
  warningName: "",
  warningDescribe: "",
  level: 0,
  enterpriseId: "",
  fileName: [],
});
const formColumns = reactive([
  {
    key: "warningName",
    type: "input",
    label: "预警名称",
    col: 24,
    tooltip: "请输入预警名称",
    disabled: false,
    clearable: true,
  },
  {
    key: "warningDescribe",
    type: "textarea",
    label: "预警描述",
    col: 24,
    clearable: true,
    rows: 4,
    tooltip: "请输入1-200个字符",
    showWordLimit: true,
    maxlength: "200",
  },
  {
    key: "level",
    type: "radio",
    label: "预警等级",
    tooltip: "请选择预警等级",
    col: 24,
    clearable: true,
    options: [
      {
        key: "高",
        value: 0,
      },
      {
        key: "中",
        value: 1,
      },
      {
        key: "低",
        value: 2,
      },
    ],
  },
  // {
  //   key: "enterpriseId",
  //   type: "cascader",
  //   label: "企业名称",
  //   tooltip: "请选择企业",
  //   allCheck: true,
  //   filterable:true,
  //   clearable:true,
  //   col: 24,
  //   options: []
  // },
  {
    key: "enterpriseId",
    label: "企业名称",
    slotName: "enterpriseId",
    col: 24,
    tooltip: "请选择企业",
  },
  {
    label: "添加附件",
    tooltip: "这里上传附件",
    col: 24,
    slotName: "fileName",
  },
]);
const rules = reactive<FormRules>({
  warningName: [{ required: true, message: "请输入预警名称", trigger: "blur" }],
  warningDescribe: [
    { required: true, message: "请输入预警名称", trigger: "blur" },
  ],
  level: [{ required: true, message: "请选择预警等级", trigger: "blur" }],
  enterpriseId: [
    { required: true, message: "请选择企业名称", trigger: "blur" },
  ],
});

let dialogForm = ref({});
let dialogType = ref("add");
let drawerProps = reactive({
  showDrawer: false,
  title: "新增预警任务",
  size: "big",
});
let dialogProps = reactive({
  showDialog: false,
  size: "",
  title: "",
  noHeader: true,
});
const drawerFormDisabled = ref(false);
const addData = () => {
  drawerFormDisabled.value = false;
  drawerProps.title = "新增预警任务";
  dialogType.value = "add";
  formData.warningName = "";
  formData.warningDescribe = "";
  formData.level = 0;
  formData.enterpriseId = "";
  formData.fileName = [];
  // uploadRef.value.fileList = [];
  drawerProps.showDrawer = true;
};
const uploadTime = ref(false);
const handleDrawerEvent = (data) => {
  const { eventName = "" } = data;
  // 抽屉点击确定按钮
  console.log(eventName);
  if (eventName === "success") {
    if (dialogType.value == "add") {
      handleConfirm();
    }
  }
};
const handleConfirm = () => {
  dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
};
const handleCloseDrawer = async (done) => {
  // if (dialogForm.value) {
  //   await dialogForm.value.resetForm(dialogForm.value.ruleFormRef);
  // }
  done();
};
const handleEvent = (data) => {
  if (data.eventName == "errorSubmit") {
    return;
  }

  if (data.eventName === "successSubmit") {
    handleFormSuccess();
    return;
  }
};
const handleFormSuccess = async () => {
  if (formData.enterpriseId) {
    formData.enterpriseId = formData.enterpriseId.toString();
    let reg1 = new RegExp("全选,", "g");
    formData.enterpriseId = formData.enterpriseId.replace(reg1, "");
  }
  // let arr = []
  if (uploadRef.value.fileList.length > 0) {
    formData.fileName = uploadRef.value.fileList.map((item) => {
      return item.fileName;
    });
  } else {
    formData.fileName = [];
  }
  let requir = "";
  if (drawerProps.title == "新增预警任务") {
    if (formData.id) {
      delete formData.id;
    }
    requir = addWarning;
  } else if (drawerProps.title == "编辑预警任务") {
    requir = updateWarning;
  }
  let parms = {
    ...formData,
  };
  if (uploadTime.value) return ElMessage.warning("附件上传中,请稍后再试！");
  let res = await requir(parms);
  if (res.code == 200) {
    if (drawerProps.title == "新增预警任务") {
      ElMessage.success("新增成功");
    } else {
      ElMessage.success("编辑成功");
    }
    drawerProps.showDrawer = false;
    search();
  }
  console.log(res);
};
// 附件上传
let fileList = ref([]);
const removedata = (uploadFile, uploadFiles) => {
  console.log(uploadFile);
};
const handleChange = async (uploadFile, uploadFiles) => {
  // uploadRef.value.fileList = uploadFiles;
  let flg = beforeAvatarUpload(uploadFile);
  if (flg) {
    uploadTime.value = true;
    let fd = new FormData();
    fd.append("file", uploadFile.raw);
    let requre = "";
    try {
      let res = await addUploadFile(fd);
      if (res.code == 200) {
        uploadRef.value.fileList[uploadRef.value.fileList.length - 1].fileName =
          res.data;
        uploadTime.value = false;
      } else {
        let _data = uploadRef.value.fileList.findIndex((item) => {
          return item.name == uploadFile.name;
        });
        uploadRef.value.fileList.splice(_data, 1);
        uploadTime.value = false;
      }
      // setTimeout(() => {
      //   uploadTime.value = false
      // },1000)
    } catch (error) {
      let _data = uploadRef.value.fileList.findIndex((item) => {
        return item.name == uploadFile.name;
      });
      uploadRef.value.fileList.splice(_data, 1);
      uploadTime.value = false;
      ElMessage.error("文件上传失败，上传文件不符合规范！");
      console.log(error, "errorerrorerror");
    }
  }
};

const beforeAvatarUpload = (file) => {
  console.log(file, "file");
  let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
  const extension2 =
    testmsg === "xlsx" ||
    testmsg === "png" ||
    testmsg === "jpg" ||
    testmsg === "pdf" ||
    testmsg === "txt" ||
    testmsg === "xls" ||
    testmsg === "doc" ||
    testmsg === "docx" ||
    testmsg === "rar" ||
    testmsg === "zip" ||
    testmsg === "wps" ||
    testmsg === "pptx";
  if (!extension2) {
    ElMessage.error("文件上传格式不正确");
    nextTick(() => {
      let _data = uploadRef.value.fileList.findIndex((item) => {
        return item.name == file.name;
      });
      uploadRef.value.fileList.splice(_data, 1);
    });
    return false;
  } else if (file.size / 1024 / 1024 > 200) {
    ElMessage.error("单个文件最多只能上传200MB!");
    nextTick(() => {
      let _data = uploadRef.value.fileList.findIndex((item) => {
        return item.name == file.name;
      });
      uploadRef.value.fileList.splice(_data, 1);
    });

    return false;
  }
  return true;
};

const getEnterpriseList = async () => {
  let res = await getEnterprise();
  if (res.code == 200) {
    // enterpriseList.value = res.data
    let arr = [
      {
        value: "全选",
        label: "全选",
        children: [],
      },
    ];
    res.data &&
      res.data.forEach((item) => {
        arr[0].children.push({
          label: item.enterpriseName,
          value: item.subjectId.toString(),
        });
      });
    optionsList.value = arr;
    formColumns.forEach((item) => {
      if (item.key == "enterpriseId") {
        // item.options = arr;
      }
    });
  }
  console.log(res);
};
// 编辑
const edit = (row) => {
  drawerProps.title = "编辑预警任务";
  // uploadRef.value.fileList = [];
  dialogType.value = "add";
  drawerFormDisabled.value = false;
  drawerProps.showDrawer = true;
  setTimeout(() => {
    nextTick(() => {
      console.log(uploadRef.value);
      formData.warningName = row.warningName;
      formData.warningDescribe = row.warningDescribe;
      formData.id = row.id;
      formData.level = row.level;
      if (row.enterpriseId) {
        formData.enterpriseId = row.enterpriseId.split(",");
      }
      formData.fileName = row.fileName;
      if (formData.fileName) {
        uploadRef.value.fileList = formData.fileName.map((item) => {
          return {
            name: item.name,
            url: item.name,
            fileName: item,
            timeStamp: item.timeStamp,
          };
        });
        // let arr = [];
        // arr = formData.fileName.split(",");
        // arr.forEach((item) => {
        //   uploadRef.value.fileList.push({
        //     name: item,
        //     url: item,
        //     fileName: item,
        //   });
        // });
        // // uploadRef.value.fileList = arr;
        // console.log(arr);
      }

      console.log(uploadRef.value.fileList, "dsdsds");
    });
  }, 200);
};
// 下发
const issueBtn = (row) => {
  dialogProps.showDialog = true;
  formData.id = row.id;
};
const sendHandleConfirm = async () => {
  let id = formData.id;
  let res = await issueWarning(id);
  if (res.code == 200) {
    dialogProps.showDialog = false;
    ElMessage.success("下发成功");
    search();
  }
};
// 详情
const viewObj = ref({});
const viewBtn = (row) => {
  console.log(row, "]][[]]");
  drawerProps.title = "预警任务详情";
  drawerFormDisabled.value = true;
  drawerProps.showDrawer = true;
  dialogType.value = "view";
  let obj = {
    title: row.warningName,
    level: row.level,
    creatorName: row.creatorName, // 创建人
    createTime: row.createTime, // 创建时间
    issueTime: row.issueTime, // 下发时间
    status: row.warningStatus,
    desObj: {
      title: "预警描述",
      content: row.warningDescribe,
    },
    enterpriseList: row.enterpriseName ? row.enterpriseName.split("、") : [],
    fileList: row.fileName,
  };
  viewObj.value = obj;
};
// 删除
const deletedata = (row) => {
  ElMessageBox.confirm("此操作不可逆，是否要确认删除？", "提示", {
    customClass: "message-warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    let idValue = row.id;
    delWarning(idValue).then((res) => {
      if (res.code == 200) {
        ElMessage.success("删除成功");
        search();
      }
    });
  });
};

const choseItem = (e) => {
  document.querySelectorAll(".el-cascader-node").forEach((el) => {
    el.click();
  });
};
const filterFun = (node, keyword) => {
  var str_1 = keyword.replace(/\s*/g, "");
  if (node.text.indexOf(str_1) != -1) {
    return true;
  }
};
const optionsList = ref([]);
const testValue = ref([]);
</script>

<template>
  <div>
    <sechdata :formColumn="formColumn" :linedata="linedata" :pieData="pieData" pietitle="任务状态分布"></sechdata>
    <div class="ya--table-type">
      <YaPageContent :formData="serchformData" :formColumns="serchColumns" :tableData="tableData" :tableColumns="column"
        searchLabelWidth="80px" :rightButtons="rightButtons" @search="search" @reset="reset"
        @tableBtnClick="tableBtnClick" :currentPage="page" :pageSize="pageSize" :total="total" @sizeChange="sizeChange"
        @currentChange="currentChange">
        <template #pageContentTop>
          <searchForm :tablist="tablist" :style="style" :clickIndex="currentTab" @handleChangeTab="handleChangeTab">
          </searchForm>
        </template>
        <!-- icon_address -->
        <template #level="{ item }">
          <span style="display: flex; align-items: center">
            <img :src="item.levelimg" style="width: 16px; height: 16px" />
            <span style="margin-left: 5px" v-html="item.levelhtml"></span>
          </span>
        </template>
        <template #status="{ item }">
          <div style="
              width: 73px;
              height: 24px;
              background: rgba(0, 0, 0, 0.05);
              border-radius: 12px;
              line-height: 24px;
              margin-top: 10px;
            ">
            <span style="
                width: 8px;
                height: 8px;
                background: #f84a51;
                display: inline-block;
                margin-left: 6px;
              " v-if="item.warningStatus == 1"></span>
            <span style="
                width: 8px;
                height: 8px;
                background: #249f2f;
                display: inline-block;
                margin-left: 6px;
              " v-if="item.warningStatus == 2"></span>
            <span style="margin-left: 6px">{{ item.warningStatusStr }}</span>
          </div>
        </template>
      </YaPageContent>
    </div>
    <!-- 新增/编辑 -->
    <ya-drawer :drawerProps="drawerProps" :showConfirm="!drawerFormDisabled" @handleEvent="handleDrawerEvent"
      destroy-on-close :before-close="handleCloseDrawer">
      <template #content>
        <ya-form v-if="dialogType == 'add'" label-position="top" @handleEvent="handleEvent" :formColumns="formColumns"
          labelWidth="100px" :formData="formData" :rules="rules" :ref="(el) => {
            if (el) dialogForm = el;
          }
            ">
          <template #enterpriseId>
            <div class="yacascader">
              <el-cascader ref="cascader" v-model="formData.enterpriseId" @visibleChange="choseItem"
                :filter-method="filterFun" placeholder="请选择企业名称" :options="optionsList" :teleported="false"
                :show-all-levels="false" :props="{
                  multiple: true,
                }" filterable />
            </div>
          </template>
          <template #fileName>
            <YaUpload :before-remove="removedata" :before-upload="beforeAvatarUpload"
              accept=".xlsx,.png,.jpg,.pdf,.txt,.xls,.doc,.docx,.rar,.zip,.wps,.pptx" :showUploadTip="false" :limit="0"
              @handleChangeUpload="handleChange" :auto-upload="false" drag ref="uploadRef" :action="''">
            </YaUpload>
          </template>
        </ya-form>
        <div v-if="dialogType == 'view'">
          <ViewDetail :viewObj="viewObj" />
        </div>
      </template>
    </ya-drawer>
    <div class="dialog-content">
      <ya-dialog :dialogProps="dialogProps">
        <template #title>
          <div>
            <i class="iconfont icon-tishi ya-primary-color"></i> 下发任务
          </div>
        </template>
        <template #content>是否确认下发?</template>
        <template #footer>
          <ya-button plain @click="dialogProps.showDialog = false">取消</ya-button>
          <ya-button type="primary" @click="sendHandleConfirm">确定</ya-button>
        </template>
      </ya-dialog>
    </div>
  </div>
</template>
<style scoped lang="scss">
::v-deep .ya-upload {
  width: 100%;
}

.icon-tishi {
  color: #0095ff;
}
</style>
