<template>
  <div>
    <base-right-dialog
      ref="baseRightDialog"
      :footerShow="true"
      :dialogVisible.sync="dialogVisible"
      :title="dialogTitle + ' 预警设置'"
      @handleClose="handleDialogClose"
      :submitShow="submitShow"
      @handleConfirmClick="handleConfirmClick"
      size="1200px"
    >
      <base-form
        ref="basicsForm"
        :formRow="formRow"
        :rules="basicsRules"
        :isFunBtn="false"
        class="dialog_form"
        :spanWidth="`120px`"
        @elDialogClick="formDialogClick"
        @onSelect="onSelect"
        @elDialogClear="elDialogClear"
      ></base-form>
      <el-button
        type="primary"
        style="margin: 10px 0"
        @click="apiSetting"
        v-if="dialogTitle != '查看'"
        >配置API</el-button
      >
      <base-table
        ref="baseTable"
        :showIndex="true"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :fixedTable="'right'"
        :funData="funData"
        @onFunc="onFunc"
        :funWidth="100"
      >
        <!-- 推送方式 -->
        <template v-slot:pushMethod="{ row }">
          <div class="w100" v-if="dialogTitle != '查看'">
            <el-select v-model="row.pushMethod" clearable>
              <el-option
                v-for="item in pushMethodList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <div class="w100" v-else>
            {{ row.pushMethod }}
          </div>
        </template>
        <!-- 状态 -->
        <template v-slot:status="{ row }">
          <div class="w100" v-if="dialogTitle != '查看'">
            <el-switch
              v-model="row.status"
              :active-value="'1'"
              :inactive-value="'0'"
              active-color="#13ce66"
            >
            </el-switch>
          </div>
          <div class="w100" v-else>
            {{ row.status == "1" ? "启用" : row.status == "0" ? "停用" : "" }}
          </div>
        </template>
      </base-table>
    </base-right-dialog>
    <base-multiple-person
      ref="baseMultiplePerson"
      @personConfirmClick="personConfirmClick"
    ></base-multiple-person>
    <base-api ref="baseApi" @apiConfirmClick="apiConfirmClick"></base-api>
  </div>
</template>

<script>
import baseRightDialog from "@/components/base/baseRightDialog";
import baseForm from "@/components/base/baseNewForm";
import baseTable from "@/components/base/baseTable";
import { getApiModuleApi } from "@/api/apiChunks/index.js";
import configData from "./configData";
import baseMultiplePerson from "./baseMultiplePerson/index.vue";
import baseApi from "./baseApi/index.vue";

export default {
  components: {
    baseRightDialog,
    baseForm,
    baseTable,
    baseMultiplePerson,
    baseApi,
  },
  data() {
    return {
      dialogVisible: false,
      dialogTitle: "",
      dialogType: "",
      formRow: configData.formRow,
      basicsRules: configData.basicsRules,
      submitShow: true,
      tableData: [],
      tableColumn: configData.tableChildColumn,
      funData: [
        {
          color: "#ff0000",
          text: "删除",
          handle: "deleteData",
        },
      ],
      apiClassificationData: [], //应用分类
      GolbelApiStr: null,
      pushMethodList: [
        {
          value: "一次",
          label: "一次",
        },
        {
          value: "定时",
          label: "定时",
        },
      ],
      billID: null,
      appArrData: [],
    };
  },
  methods: {
    openDialog(type, row = {}) {
      this.dialogVisible = true;
      this.billID = row ? row.id : null;
      this.formRow = configData.formRow;
      this.basicsRules = configData.basicsRules
      this.funData = [
        {
          color: "#ff0000",
          text: "删除",
          handle: "deleteData",
        },
      ];
      if (type == "add") {
        this.dialogTitle = "新增";
      }
      if (type == "edit") {
        this.dialogTitle = "修改";
      }
      if (type == "show") {
        this.dialogTitle = "查看";
        this.formRow = configData.formRowShow;
        this.funData = [];
        this.basicsRules = {}
      }
      if (type != "show") {
        this.getMessageList();
        this.getApplicationList();
        this.getSendMethods();
      }
      if (row.id) {
        this.getDetails(row.id);
      }
    },
    // 详情
    async getDetails(id) {
      const res = await getApiModuleApi(
        {
          tl: "sysWarningConfigService",
          as: "",
          dj: "getEntity",
        },
        {
          id: id,
        }
      );
      if (res.status == "200") {
        this.$nextTick(() => {
          this.GolbelApiStr = res.attribute.father.appIdList;
          let appList = res.attribute.father.appIdList.split(",");
          // 根据所选择的id 找到所属应用分类
          const result = this.appArrData
            .filter((item) => appList.includes(item.id)) // 过滤出匹配的id
            .map((item) => ({ id: item.id, label: item.name })); // 生成id和appName的对象
          this.apiClassificationData = [
            { id: res.attribute.father.appIdList, label: "全部" },
            ...result,
          ];
          res.attribute.father.appIdList = appList;
          res.attribute.father.warningAppId =
            res.attribute.father.warningAppId.split(",");
          this.$refs.basicsForm.incomingParameters(res.attribute.father);
          this.tableData = res.attribute.son;
        });
      }
    },
    formDialogClick(row, index) {
      if (row.label == "接收人") {
        let data = this.$refs.basicsForm.ruleForm;

        if (data.recipientNameList && data.recipientIdList) {
          const ids = data.recipientIdList.split(",");
          const names = data.recipientNameList.split(",");
          const result = ids.map((id, index) => ({
            id: id,
            personName: names[index],
          }));
          this.$refs.baseMultiplePerson.openDialog(result);
        } else {
          this.$refs.baseMultiplePerson.openDialog();
        }
      }
    },
    personConfirmClick(row) {
      let idList = "",
        nameList = "";
      if (row.length > 0) {
        let ids = [],
          names = [];
        row.forEach((el) => {
          names.push(el.personName);
          ids.push(el.id);
        });
        idList = ids.join(",");
        nameList = names.join(",");
      }
      this.$refs.basicsForm.getField("recipientNameList", nameList);
      this.$refs.basicsForm.getField("recipientIdList", idList);
    },
    elDialogClear(row, index) {
      if (row.label == "接收人") {
        this.$refs.basicsForm.getField("recipientNameList", "");
        this.$refs.basicsForm.getField("recipientIdList", "");
      }
    },
    onSelect(val, index, indexRow, obj, options, data, row) {
      if (row.label == "推送方式") {
        const foundItem = options.filter((item) => val.includes(item.id));
        if (foundItem.length > 0) {
          let messageStr = "";
          let messageApi = [];
          foundItem.forEach((el) => {
            messageApi.push(el.messageApi);
          });
          messageStr = messageApi.join(",");
          this.$refs.basicsForm.getField("acceptMessageApiCode", messageStr);
        } else {
          this.$refs.basicsForm.getField("acceptMessageApiCode", "");
        }
      }
      if (row.label == "应用") {
        let str = val.join(",");
        this.GolbelApiStr = str;
        // 根据所选择的id 找到所属应用分类
        const result = options
          .filter((item) => val.includes(item.id)) // 过滤出匹配的id
          .map((item) => ({ id: item.id, label: item.name })); // 生成id和appName的对象
        this.apiClassificationData = [{ id: str, label: "全部" }, ...result];

        // 处理数据
        if (this.tableData.length > 0) {
          let filteredData = this.tableData.filter((item) =>
            val.includes(item.appId)
          );
          this.tableData = filteredData;
        }
      }
    },
    apiSetting() {
      if (
        this.GolbelApiStr == null ||
        this.GolbelApiStr == "" ||
        this.GolbelApiStr == undefined
      ) {
        this.$vmNews("请选择应用", "warning");
        return;
      }
      this.$refs.baseApi.openDialog(
        this.GolbelApiStr,
        this.apiClassificationData,
        this.tableData
      );
    },
    apiConfirmClick(rows) {
      //这边需要先做去重再往里加 将没有的加进tempTable
      let tempTable = [];
      //所有incove
      let tempArr = [];
      this.tableData.forEach((item) => {
        tempArr.push(item.apiCode);
      });
      this.tableData = [];
      rows.forEach((item) => {
        if (!tempArr.includes(item.apiCode)) {
          tempTable.push(item);
        } else {
          //如果存在则不需要处理 放回去
          this.tableData.push(item);
        }
      });
      // 正式开始添加
      tempTable.forEach((item) => {
        let arr = {
          apiCode: item.apiCode,
          apiName: item.apiName,
          appName: item.appName,
          appId: item.appId,
          pushMethod: "一次",
          status: "0",
        };
        this.tableData.push(arr);
      });
    },
    // 获取消息模版
    async getMessageList() {
      const res = await getApiModuleApi(
        {
          tl: "sysMessageTemplateService",
          as: "",
          dj: "queryEntity",
        },
        {
          state: "1"
        }
      );
      if (res.status == "200") {
        this.formRow[0].elCol[0].options = res.attribute;
      }
    },
    // 获取所有应用
    async getApplicationList() {
      const res = await getApiModuleApi(
        {
          tl: "sysApplicationService",
          as: "",
          dj: "queryEntity",
        },
        {}
      );
      if (res.status == "200") {
        this.appArrData = res.attribute;
        this.formRow[0].elCol[1].options = res.attribute;
      }
    },
    // 获取推送方式
    async getSendMethods() {
      const res = await getApiModuleApi(
        {
          tl: "sysApplicationService",
          as: "",
          dj: "queryEntity",
        },
        {
          appType: "5DD",
        }
      );
      if (res.status == "200") {
        res.attribute.forEach((item) => {
          if ((item.id = "7ebc1702511f463d9cf50162973bf935")) {
            item.messageApi = "8000430001";
          }
        });
        this.sendMessage = res.attribute;
        this.formRow[1].elCol[1].options = res.attribute;
      }
    },
    // 编辑详情
    async productGetById(id) {
      let params = {
        id: id,
      };
      const res = await getApiModuleApi(
        {
          tl: "sysSendMessageLogService",
          as: "",
          dj: "getEntity",
        },
        {
          ...params,
        }
      );
      if (res.status == "200") {
        this.$nextTick(() => {
          this.$refs.basicsForm.incomingParameters(res.attribute);
        });
      }
    },
    // 子表行操作
    onFunc(index, row, item) {
      this[item.handle](index, row, item);
    },
    // 子表删除
    deleteData(index, row, item) {
      this.tableData.splice(row.index, 1);
    },
    handleConfirmClick() {
      this.$refs.basicsForm.$refs["ruleForm"].validate((valid) => {
        if (!valid) {
          this.$tipConfirm("请输入必填项");
          return;
        } else {
          let data = this.$refs.basicsForm.ruleForm;
          let params = {
            father: {
              ...data,
              status: "1",
            },
            son: this.tableData,
          };
          params.father.appIdList = params.father.appIdList.join(",");
          params.father.warningAppId = params.father.warningAppId.join(",");
          this.openLoading("submit");
          if (
            this.billID != "" &&
            this.billID != null &&
            this.billID != undefined
          ) {
            this.updateWarningSetting(params);
          } else {
            // 新增
            this.saveWarningSetting(params);
          }
        }
      });
    },
    async saveWarningSetting(param) {
      const res = await getApiModuleApi(
        {
          tl: "sysWarningConfigService",
          as: "",
          dj: "saveEntity",
        },
        {
          ...param,
        }
      );
      this.tabLoading = false;
      if (res.status == "200") {
        this.$vmNews("新增成功", "success");
        this.handleDialogClose();
        this.$emit("resetTable");
      }
    },
    async updateWarningSetting(param) {
      const res = await getApiModuleApi(
        {
          tl: "sysWarningConfigService",
          as: "",
          dj: "updateEntity",
        },
        {
          ...param,
        }
      );
      this.tabLoading = false;
      if (res.status == "200") {
        this.$vmNews("修改成功", "success");
        this.handleDialogClose();
        this.$emit("resetTable");
      }
    },
    // 弹窗关闭
    handleDialogClose() {
      this.GolbelApiStr = null;
      this.tableData = Object.assign([], []);
      this.$refs.basicsForm.resetFields();
      this.dialogVisible = false;
    },
  },
};
</script>

<style scoped lang="scss">
.dialogList {
  padding: 16px 0;
  border-top: 1px solid #dcdfe6;
  display: flex;
  flex-direction: column;
}

.w100 {
  width: 100%;
}
.updateBtn {
  border: 1px solid #ebedf1;
  padding: 5px 0;
  border-radius: 3px;
  text-align: center;
  font-size: 14px;
  cursor: pointer;
  width: 100px;
}

.updateBtn:hover {
  color: #1890ff;
  border-color: #badeff;
  background-color: #e8f4ff;
}
::v-deep .el-table__body-wrapper {
  height: auto !important;
}

::v-deep .app-container {
  height: auto !important;
}
</style>
