<template>
  <div class="page-wrapper">
    <!-- 任务推送配置 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <!-- 参数预警配置 -->
      <a-collapse
        default-active-key="d"
        expand-icon-position="right"
        class="collapse-header-divide"
      >
        <a-collapse-panel
          key="d"
          :header="$t('PARAMETER_ALERT_CONFIGURATION')"
          :show-arrow="false"
          disabled
        >
          <a-row :gutter="24" type="flex">
            <a-col :span="13">
              <a-form-model-item :label="$t('PUSH_MODE')" prop="paramPushMode">
                <a-checkbox-group
                  v-model="form.paramPushMode"
                  :disabled="!isEdit"
                >
                  <a-checkbox value="EMAIL" name="type">
                    {{ $t("EMAIL") }}
                  </a-checkbox>
                  <a-checkbox value="WORK_WX" name="type">
                    {{ $t("WECHAT") }}
                  </a-checkbox>
                </a-checkbox-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="13">
              <a-form-model-item
                :label="$t('RECEIVER_GROUP')"
                prop="paramReceiverGroup"
              >
                <div style="display: flex">
                  <SelectSearch
                    key="c"
                    :disabled="!isEdit"
                    :show-multiple="false"
                    request-api="/api/msg/receiver-group/search"
                    :show-red-border="showRedBorder"
                    option-label="groupName"
                    query-list-key="id"
                    :default-selected-keys="form.paramReceiverGroup"
                    :default-selected-names="form.paramGroupName"
                    style="width: 100%"
                    @change="
                      (e) => onSelectSearchChange(e, 'paramReceiverGroup')
                    "
                  >
                  </SelectSearch>
                  <div
                    v-if="isEdit"
                    class="jump-box"
                    style="cursor: pointer"
                    @click="jumpToAdd('receiverGroup')"
                  >
                    <a-icon type="right" />
                  </div>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-collapse-panel>
      </a-collapse>
      <!-- 能源预警配置 -->
      <a-collapse
        default-active-key="e"
        expand-icon-position="right"
        class="collapse-header-divide"
        style="margin-bottom: 70px"
      >
        <a-collapse-panel
          key="e"
          :header="$t('ENERGY_EARLY_WARNING_CONFIGURATION')"
          :show-arrow="false"
          disabled
        >
          <a-row :gutter="24" type="flex">
            <a-col :span="13">
              <a-form-model-item :label="$t('PUSH_MODE')" prop="powerPushMode">
                <a-checkbox-group
                  v-model="form.powerPushMode"
                  :disabled="!isEdit"
                >
                  <a-checkbox value="EMAIL" name="type">
                    {{ $t("EMAIL") }}
                  </a-checkbox>
                  <a-checkbox value="WORK_WX" name="type">
                    {{ $t("WECHAT") }}
                  </a-checkbox>
                </a-checkbox-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="13">
              <a-form-model-item
                :label="$t('RECEIVER_GROUP')"
                prop="powerReceiverGroup"
              >
                <div style="display: flex">
                  <SelectSearch
                    key="c"
                    :disabled="!isEdit"
                    :show-multiple="false"
                    request-api="/api/msg/receiver-group/search"
                    :show-red-border="showRedBorder"
                    option-label="groupName"
                    query-list-key="id"
                    :default-selected-keys="form.powerReceiverGroup"
                    :default-selected-names="form.powerGroupName"
                    style="width: 100%"
                    @change="
                      (e) => onSelectSearchChange(e, 'powerReceiverGroup')
                    "
                  >
                  </SelectSearch>
                  <div
                    v-if="isEdit"
                    class="jump-box"
                    style="cursor: pointer"
                    @click="jumpToAdd('receiverGroup')"
                  >
                    <a-icon type="right" />
                  </div>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-collapse-panel>
      </a-collapse>
    </a-form-model>
    <div class="page-bottom-op">
      <a-button v-show="isEdit" type="primary" @click="handleSubmit()">
        <i class="iconfont icon-baocun" />
        {{ $t("SAVE") }}
      </a-button>
      <a-button v-show="isEdit" @click="handleCancel()">
        <i class="iconfont icon-quxiao" />
        {{ $t("CANCEL") }}
      </a-button>
      <a-button v-show="!isEdit" type="primary" @click="handleEdit()">
        <i class="iconfont icon-baocun" />
        {{ $t("EDIT") }}
      </a-button>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { cloneDeep } from "lodash";
import ApiConstant from "@/api/ApiConstant";
import FieldExtendMixin from "@/mixins/fieldExtend";

import SelectSearch from "@/components/epms/SelectSearch";

export default {
  components: { SelectSearch },
  mixins: [FieldExtendMixin],
  data() {
    return {
      // 编辑状态
      isEdit: false,
      // 邮件服务器集合
      emailList: [],
      // 企业微信集合
      wechatList: [],
      form: {
        id: "",
        email: "",
        wechat: "",
        checkPushTime: "00:00",
        checkPushMode: [],
        checkReceiverGroup: "",
        mainPushTime: "00:00",
        mainPushMode: [],
        mainReceiverGroup: "",
        paramPushMode: [],
        paramReceiverGroup: "",
        powerPushMode: [],
        powerReceiverGroup: "",
      },
      formOld: {},
    };
  },
  computed: {
    ...mapState({
      showRedBorder: (state) => state.pagination.showRedBorder,
    }),
    extandParams() {
      const {
        id,
        email,
        wechat,
        checkPushTime,
        checkPushMode,
        checkReceiverGroup,
        mainPushTime,
        mainPushMode,
        mainReceiverGroup,
        paramPushMode,
        paramReceiverGroup,
        powerPushMode,
        powerReceiverGroup,
      } = this.form;
      const options = {
        id,
      };
      options.pushConfigList = [];
      options.pushServerList = [];
      if (checkPushTime || checkPushMode?.length || checkReceiverGroup) {
        options.pushConfigList.push({
          configType: "DELAY",
          funcType: "PC",
          pushTime: checkPushTime,
          pushTypeList: checkPushMode,
          receiverGroupId: checkReceiverGroup,
        });
      }
      if (mainPushTime || mainPushMode?.length || mainReceiverGroup) {
        options.pushConfigList.push({
          configType: "DELAY",
          funcType: "PM",
          pushTime: mainPushTime,
          pushTypeList: mainPushMode,
          receiverGroupId: mainReceiverGroup,
        });
      }
      if (paramPushMode?.length || paramReceiverGroup) {
        options.pushConfigList.push({
          configType: "HURRY",
          funcType: "PARAM",
          pushTypeList: paramPushMode,
          receiverGroupId: paramReceiverGroup,
        });
      }
      if (powerPushMode?.length || powerReceiverGroup) {
        options.pushConfigList.push({
          configType: "HURRY",
          funcType: "POWER",
          pushTypeList: powerPushMode,
          receiverGroupId: powerReceiverGroup,
        });
      }
      if (
        email ||
        mainPushMode.includes("EMAIL") ||
        checkPushMode.includes("EMAIL") ||
        paramPushMode.includes("EMAIL") ||
        powerPushMode.includes("EMAIL")
      ) {
        options.pushServerList.push({
          pushServerId: email,
          pushType: "EMAIL",
        });
      }
      if (
        wechat ||
        mainPushMode.includes("WORK_WX") ||
        checkPushMode.includes("WORK_WX") ||
        paramPushMode.includes("WORK_WX") ||
        powerPushMode.includes("WORK_WX")
      ) {
        options.pushServerList.push({
          pushServerId: wechat,
          pushType: "WORK_WX",
        });
      }
      return options;
    },
    isRequired() {
      let isRequired = false;
      const { checkPushTime, checkPushMode, checkReceiverGroup } = this.form;
      if (checkPushTime || checkPushMode?.length || checkReceiverGroup) {
        isRequired = true;
      }
      return isRequired;
    },
    isRequired2() {
      let isRequired = false;
      const { mainPushTime, mainPushMode, mainReceiverGroup } = this.form;
      if (mainPushTime || mainPushMode?.length || mainReceiverGroup) {
        isRequired = true;
      }
      return isRequired;
    },
    isRequired3() {
      let isRequired = false;
      const { paramPushMode, paramReceiverGroup } = this.form;
      if (paramPushMode?.length || paramReceiverGroup) {
        isRequired = true;
      }
      return isRequired;
    },
    isRequired4() {
      let isRequired = false;
      const { powerPushMode, powerReceiverGroup } = this.form;
      if (powerPushMode?.length || powerReceiverGroup) {
        isRequired = true;
      }
      return isRequired;
    },
    rules() {
      return {
        email: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        wechat: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        checkPushTime: [
          {
            required: this.isRequired,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        checkPushMode: [
          {
            type: "array",
            required: this.isRequired,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        checkReceiverGroup: [
          {
            required: this.isRequired,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        mainPushTime: [
          {
            required: this.isRequired2,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        mainPushMode: [
          {
            type: "array",
            required: this.isRequired2,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        mainReceiverGroup: [
          {
            required: this.isRequired2,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        paramPushMode: [
          {
            type: "array",
            required: this.isRequired3,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        paramReceiverGroup: [
          {
            required: this.isRequired3,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        powerPushMode: [
          {
            type: "array",
            required: this.isRequired4,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        powerReceiverGroup: [
          {
            required: this.isRequired4,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  mounted() {
    Promise.all([
      this.$axios.get(`${ApiConstant.PREFIX_CORE}/api/msg/email-server/list`),
      this.$axios.get(
        `${ApiConstant.PREFIX_CORE}/api/msg/wechat-enterprise/list`
      ),
    ]).then(([emailRes, wechatRes]) => {
      this.emailList = emailRes.data.data;
      this.wechatList = wechatRes.data.data;
      this.getPushConfig();
    });
  },
  methods: {
    // 获取推送配置数据
    getPushConfig() {
      // @param factoryCode 工厂编码
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/ebs/push-config/detail`)
        .then((res) => {
          const form = this.fieldExResDataFn(res.data?.data);
          const { id, pushServerList, pushConfigList } = form;
          const email =
            pushServerList?.find((item) => item.pushType === "EMAIL")
              ?.pushServerId || "";
          const wechat =
            pushServerList?.find((item) => item.pushType === "WORK_WX")
              ?.pushServerId || "";
          const checkConfig = pushConfigList.find(
            (item) => item.funcType === "PC"
          );
          const mainConfig = pushConfigList.find(
            (item) => item.funcType === "PM"
          );
          const paramConfig = pushConfigList.find(
            (item) => item.funcType === "PARAM"
          );
          const powerConfig = pushConfigList.find(
            (item) => item.funcType === "POWER"
          );
          this.form = {
            id,
            email,
            wechat,
            checkPushTime: checkConfig?.pushTime || "00:00",
            checkPushMode: checkConfig?.pushTypeList || [],
            checkReceiverGroup: checkConfig?.receiverGroupId,
            mainPushTime: mainConfig?.pushTime || "00:00",
            mainPushMode: mainConfig?.pushTypeList || [],
            mainReceiverGroup: mainConfig?.receiverGroupId,
            paramPushMode: paramConfig?.pushTypeList || [],
            paramReceiverGroup: paramConfig?.receiverGroupId,
            powerPushMode: powerConfig?.pushTypeList || [],
            powerReceiverGroup: powerConfig?.receiverGroupId,
          };
          this.formOld = {
            ...this.form,
            ...this.formOld,
          };
        });
    },
    // 接收组选中
    onSelectSearchChange(e, groupId) {
      this.form[groupId] = e;
    },
    // 跳转其他页面新增数据
    jumpToAdd(name) {
      this.$router.push({
        query: {
          openAdd: true,
        },
        path: `/upms/service/message/${name}`,
      });
    },
    // 取消
    handleCancel(e) {
      this.isEdit = false;
      this.form = cloneDeep(this.formOld);
    },
    // 编辑
    handleEdit(e) {
      this.isEdit = true;
      this.formOld = cloneDeep(this.form);
    },
    // 保存
    handleSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const options = this.extandParams;
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/epm/ebs/push-config`, options)
            .then(() => {
              this.isEdit = false;
              this.$message.success(this.$t("EDIT_SUCCESS"));
              this.getPushConfig();
            });
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.jump-box {
  margin-left: 10px;
  color: #999;
  line-height: 34px;
  padding: 0 5px;
  border: 1px solid #ccc;
}
</style>
