<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :total="total"
      :page.sync="page"
      :action-buttons="actionButtons"
      :mega-extend="{
        rowAction: {
          width: 120,
        },
      }"
      @beforeSearch="beforeSearch"
      @search="searchPageData"
      @edit="handleEdit"
      @delete="handleDelete"
      @reset="handleReset"
    >
      <a-row slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('EPROPEL_WORK:ADD')"
          icon="plus"
          @click="handleAdd"
        >
          {{ $t("ADD") }}
        </a-button>
      </a-row>
      <template slot="status" slot-scope="text">
        <span>
          <!-- {{ formatData(statusList, text) }} -->
          {{ getAttrValue(statusList, text) }}
        </span>
      </template>
    </MomTable>

    <!-- 推送 pushFlag -->
    <MegaDrawer
      width="520"
      :title="$t('PUSH')"
      :visible.sync="pushFlag"
      @close="pushFlag = false"
      @ok="handlePushSave"
      @cancel="handlePushCancel"
    >
      <!-- :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }" -->
      <a-form-model
        slot="main"
        ref="pushDrawerForm"
        :rules="pushFormRules"
        :model="pushForm"
      >
        <a-row>
          <a-col :span="24">
            <a-form-model-item :label="$t('UNSOFTWARECODE')" prop="eqpSn">
              <a-input
                v-model="pushForm.eqpSn"
                disabled
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item :label="$t('EQPCODE')" prop="eqpCode">
              <a-input
                v-model="pushForm.eqpCode"
                disabled
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item> </a-col
        ></a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('CHOOSEINFO')"
              :rules="{
                message: $t('PLACESELECT'),
                trigger: 'blur',
                required: true,
              }"
              prop="msgId"
            >
              <a-select
                v-model="pushForm.msgId"
                show-search
                :filter-option="filterOption"
                :placeholder="$t('PLACESELECT')"
                @change="chan"
              >
                <a-select-option
                  v-for="item in chooseInfoList"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col></a-row
        >
      </a-form-model>
    </MegaDrawer>

    <MegaDrawer
      width="520"
      :title="actionType === 'add' ? $t('ADD') : $t('EDIT')"
      :visible.sync="megaDrawerVisible"
      @close="megaDrawerVisible = false"
      @ok="handleImportSave"
      @cancel="handleImportCancel"
    >
      <!-- :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }" -->
      <a-form-model slot="main" ref="EqpDrawerForm" :model="formEqp">
        <a-row>
          <a-col :span="24">
            <a-form-model-item
              :rules="{
                max: 32,
                message: $t('PLACEENTER') + 32 + $t('LENGTH_TIP'),
                trigger: 'blur',
                required: false,
              }"
              :label="$t('EQPCODE')"
              prop="eqpName"
            >
              <a-input
                v-model="formEqp.eqpCode"
                :disabled="ifdisabled"
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item
              :rules="{
                max: 32,
                message: $t('PLACEENTER') + 32 + $t('LENGTH_TIP'),
                trigger: 'blur',
                required: true,
              }"
              :label="$t('EQUIPMENT_NAME')"
              prop="eqpName"
            >
              <a-input
                v-model="formEqp.eqpName"
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item
              :rules="{
                max: 255,
                message: $t('PLACEENTER') + 255 + $t('LENGTH_TIP'),
                trigger: 'blur',
                required: false,
              }"
              :label="$t('REMARK')"
              prop="remark"
            >
              <div class="tdp">
                <a-input
                  v-model="formEqp.remark"
                  :placeholder="$t('PLACEENTER')"
                  type="textarea"
                />
              </div>
            </a-form-model-item> </a-col
        ></a-row>
      </a-form-model>
    </MegaDrawer>
  </div>
</template>

<script>
import ApiConstant from "@/api/ApiConstant";
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";

export default {
  components: {
    Icon,
    MegaDrawer,
  },
  data() {
    return {
      ifdisabled: false,
      actionId: "",
      actionType: "add",
      pushForm: {
        eqpSn: "",
        eqpCode: "",
        msgId: "",
      },
      chooseInfoList: [],
      formEqp: {
        eqpCode: "",
        eqpName: "",
        remark: "",
      },
      megaDrawerVisible: false,
      pushFlag: false,
      tableData: [],
      page: 1, // 页码
      total: 0, // 每页个数
      title: "", // 弹框的标题
      statusList: [],
      queryForm: {
        // 消息编码
        eqpCode: "",
        // 消息名称
        eqpName: "",
      },
      actionButtons: [
        this.hasAuth("EPROPEL_WORK:EDIT") && "edit",
        (h, { record }) =>
          this.hasAuth("EPROPEL_WORK:SEND") && (
            <span
              class="text-primary cursor-pointer"
              title={this.$t("PUSH")}
              onClick={() => this.pushShow(record)}>
              <a-icon
                class="operation-icon text-edit-blue text-15"
                type="cloud"
              />
            </span>
          ),
        //  icon-ins-check-circle
        this.hasAuth("EPROPEL_WORK:DELETE") && "delete",
      ],
      // 表格的配置项
      tableColumns: [
        {
          dataIndex: "eqpCode",
          align: "left",
          width: 180,
          sorter: true,
          ellipsis: true,
          title: () => this.$t("EQPCODE"), // 设备编码
        },
        {
          dataIndex: "eqpName",
          align: "left",
          width: 180,
          title: () => this.$t("EQUIPMENT_NAME"), // 设备名称
          ellipsis: true,
          sorter: true,
        },
        {
          dataIndex: "eqpSn",
          align: "left",
          sorter: true,
          width: 180,
          title: () => this.$t("UNSOFTWARECODE"), // 硬件序列号
          ellipsis: true,
        },
        {
          dataIndex: "status",
          align: "left",
          sorter: false,
          width: 100,
          title: () => this.$t("STATE"), // 状态
          scopedSlots: { customRender: "status" },
          ellipsis: true,
        },
        {
          dataIndex: "lastConnectTime", // 最后连接时间
          title: () => this.$t("LAST_CONNECTION_TIME"),
          width: 180,
          sorter: true,
          ellipsis: true,
        },
        {
          dataIndex: "msgCode", // 当前消息编号
          title: () => this.$t("CURRENTINFOCODE"),
          width: 180,
          sorter: false,
          ellipsis: true,
        },
        {
          dataIndex: "msgName", // 当前消息名称
          title: () => this.$t("CURRENTINFONAME"),
          width: 180,
          sorter: false,
          ellipsis: true,
        },
        {
          dataIndex: "remark",
          align: "left",
          sorter: false,
          width: 600,
          title: () => this.$t("REMARK"), // 备注
          ellipsis: true,
        },
      ],
    };
  },
  computed: {
    pushFormRules() {
      // eslint-disable-next-line
      const temp_obj = {
        chooseinfo: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      };
      // eslint-disable-next-line
      return temp_obj;
    },
    // 表格搜索配置项
    queryFormItem() {
      return {
        eqpCode: {
          label: () => this.$t("EQPCODE"), // 编码
          itemType: "input",
        },
        eqpName: {
          label: () => this.$t("EQUIPMENT_NAME"), // 名称
          itemType: "input",
        },
      };
    },
    rules() {
      return {};
    },
  },
  created() {},
  mounted() {
    // this.afterChange(0);
  },
  methods: {
    chan(val) {
      // console.log(this.pushForm.msgId);
    },
    handleAudit(state) {},
    disableChildDictLeft(row, state, a, b, tips) {
      this.$confirm({
        title: this.$t(a),
        content: this.$t(b),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          row.enableFlag = state;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/epropeltask/enable/${row.id}/${state}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text
        .toLowerCase()
        .includes(input.toLowerCase());
    },
    // 在线发送
    onlineSend() {
      const params = { msgId: this.pushForm.msgId };
      this.$axios
        .post(
          `${ApiConstant.PREFIX_CORE}/api/epropeltask/${this.actionId}`,
          null,
          { params }
        )
        .then((res) => {
          if (res.data.success) {
            this.pushFlag = false;
            this.$message.success(this.$t("PUSH_SUCCESS"));
            this.pushForm.eqpSn = "";
            this.pushForm.eqpCode = "";
            this.pushForm.msgId = "";
            this.$refs.MomTable?.query();
          }
        });
    },
    handlePushSave() {
      this.$refs.pushDrawerForm.validate((valid) => {
        if (valid) {
          // 判断设备是否在线
          this.$axios
            .get(
              `${ApiConstant.PREFIX_CORE}/api/epropeltask/is-online/${this.actionId}`
            )
            .then((res) => {
              if (res.data.data) {
                this.onlineSend();
              } else {
                // 离线
                this.$confirm({
                  title: this.$t("CONFIRM_MATION"),
                  content: this.$t("OFFLINE_PUSH_INFO"),
                  okType: "warning",
                  okText: this.$t("CONFIRM"),
                  cancelText: this.$t("CANCEL"),
                  centered: false,
                  icon: "exclamation-circle",
                  onOk: () => {
                    const params = { id: this.actionId, ...this.pushForm };
                    this.$axios
                      .put(`${ApiConstant.PREFIX_CORE}/api/epropeltask`, params)
                      .then((res) => {
                        if (res.data.success) {
                          this.pushFlag = false;
                          this.$message.success(this.$t("PUSH_SUCCESS"));
                          this.pushForm.eqpSn = "";
                          this.pushForm.eqpCode = "";
                          this.pushForm.msgId = "";
                          this.$refs.MomTable?.query();
                        }
                      });
                  },
                });
              }
            });
        } else {
          // this.$message.error(this.$t("REQUIRED_INFO"));
        }
      });
    },
    handlePushCancel() {
      this.pushFlag = false;
    },
    handleImportSave() {
      if (this.actionType === "add") {
        this.ifdisabled = false;
        this.$refs.EqpDrawerForm.validate((valid) => {
          if (valid) {
            const params = { ...this.formEqp };
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/epropeltask`, params)
              .then((res) => {
                if (res.data.success) {
                  this.megaDrawerVisible = false;
                  this.$message.success(this.$t("ADD_SUCCESS"));
                  this.formEqp.eqpName = "";
                  this.formEqp.remark = "";
                  this.formEqp.eqpCode = "";
                  this.$refs.MomTable?.query();
                }
              });
          } else {
            // this.$message.error(this.$t("REQUIRED_INFO"));
          }
        });
      } else {
        this.ifdisabled = true;
        this.$refs.EqpDrawerForm.validate((valid) => {
          if (valid) {
            const params = { id: this.actionId, ...this.formEqp };
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/epropeltask`, params)
              .then((res) => {
                if (res.data.success) {
                  this.megaDrawerVisible = false;
                  this.$message.success(this.$t("EDIT_SUCCESS"));
                  this.formEqp.eqpName = "";
                  this.formEqp.remark = "";
                  this.formEqp.eqpCode = "";
                  this.$refs.MomTable?.query();
                }
              });
          } else {
            // this.$message.error(this.$t("REQUIRED_INFO"));
          }
        });
      }
    },
    handleImportCancel() {
      this.formEqp.eqpName = "";
      this.formEqp.remark = "";
      this.formEqp.eqpCode = "";
      this.megaDrawerVisible = false;
    },
    closePreview() {
      this.pushFlag = false;
    },
    pushShow(row) {
      this.actionId = row.id;
      this.pushForm.eqpSn = row.eqpSn;
      this.pushForm.eqpCode = row.eqpCode;
      const params = {
        enableFlag: "Y",
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epropelmsg/list`, {
          params,
        })
        .then((res) => {
          this.chooseInfoList = [];
          const arr = res.data.data;
          arr.forEach((item, index) => {
            this.chooseInfoList.push({
              label: item.msgName,
              value: item.id,
            });
          });
          this.pushForm.msgId = row.msgId;
        });
      this.pushFlag = true;
    },
    // 查询数据字典
    beforeSearch() {
      return Promise.all([
        this.getDictByCode(`DIC:IOT:CONNECT_STATUS`), // 状态
      ]).then(([enableStatusRes]) => {
        this.statusList = enableStatusRes.data.data;
      });
    },
    // 重置
    handleReset() {
      this.$refs.MomTable?.query();
    },
    // 后台分页查询
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epropeltask/search`, {
          params,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = parseFloat(res.data.data.total);
        });
    },
    // 点击新增
    handleAdd() {
      this.actionType = "add";
      this.ifdisabled = false;
      this.megaDrawerVisible = true;
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      this.actionId = row.id;
      this.actionType = "edit";
      this.ifdisabled = true;
      this.megaDrawerVisible = true;
      this.formEqp.eqpName = row.eqpName;
      this.formEqp.remark = row.remark;
      this.formEqp.eqpCode = row.eqpCode;
    },
    // 点击表格行内的删除
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/epropeltask/${row.id}`)
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.page = 1;
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.cursor-pointer {
  cursor: pointer;
}
/deep/.ant-modal-footer {
  padding: 10px 16px;
  text-align: right;
  background: transparent;
  border-top: 1px solid #f0f0f0;
  border-radius: 0 0 4px 4px;
  display: none;
}
</style>
