<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :total="total"
      :page.sync="page"
      :action-buttons="actionButtons"
      :show-enable-flag="true"
      @beforeSearch="beforeSearch"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="searchPageData"
      @enable="
        (record) =>
          handleStatus(
            { status: 'Y', id: record.id },
            'ENABLED',
            'ENABLED_DATA_INFO',
            'ENABLE_SUCCESS'
          )
      "
      @disable="
        (record) =>
          handleStatus(
            { status: 'N', id: record.id },
            'DISABLED',
            'DISABLED_DATA_INFO',
            'DISABLE_SUCCESS'
          )
      "
    >
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('WECHAT_OFFICIAL_ACCOUNT:ADD')"
          type="primary"
          @click="handleAdd"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('WECHAT_OFFICIAL_ACCOUNT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <template slot="enableFlag" slot-scope="text">
        <span :class="text === 'Y' ? 'text-success' : 'text-error'">
          {{ formatData(statusList, text) }}
        </span>
      </template>
      <template slot="isSystemConfig" slot-scope="text">
        <span :class="text === 'Y' ? 'text-success' : 'text-error'">
          {{ formatData(whetherCharList, text) }}
        </span>
      </template>
    </MomTable>
    <MegaDrawer
      :visible="drawerVisible"
      :title="form.id ? $t('EDIT') : $t('ADD')"
      width="520"
      @close="handleClose"
    >
      <template slot="main">
        <a-form-model
          ref="addForm"
          layout="vertical"
          :model="form"
          :rules="rules"
        >
          <a-row>
            <a-col :span="24">
              <a-form-model-item
                :label="$t('OFFICIAL_ACCOUNT_CODE')"
                prop="serverCode"
              >
                <a-input
                  v-model="form.serverCode"
                  :disabled="form.id !== null && form.id !== ''"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                :label="$t('OFFICIAL_ACCOUNT_NAME')"
                prop="serverName"
              >
                <a-input v-model="form.serverName" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :label="$t('DEVELOPER_ID')" prop="appId">
                <a-input v-model="form.appId" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :label="$t('DEVELOPER_KEY')" prop="appSecret">
                <a-input v-model="form.appSecret" type="password" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                :label="$t('BIND_TO_USE')"
                prop="isSystemConfig"
              >
                <a-radio-group v-model="form.isSystemConfig">
                  <a-radio value="Y">{{ $t("YES") }}</a-radio>
                  <a-radio value="N">{{ $t("NO") }}</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </template>
      <footer slot="footer">
        <a-button type="primary" @click="handleSave()">
          <Icon type="icon-cur-save_1" :size="18" />{{ $t("SAVE") }}
        </a-button>
        <a-button @click="handleClose">
          <Icon type="icon-dir-f-rollback" :size="18" />{{ $t("CANCEL") }}
        </a-button>
      </footer>
    </MegaDrawer>
  </div>
</template>
<script>
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      title: "", // 弹框标题
      drawerVisible: false, // 新增修改的弹框
      // 查询sort
      tableData: [], // 表格数据
      page: 1, // 分页第几页
      total: 0, // 数据表格总条数
      form: {
        id: "",
        serverCode: "",
        serverName: "",
        appId: "",
        appSecret: "",
        isSystemConfig: "N",
      },
      rules: {
        serverCode: [
          {
            max: 32,
            required: false,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        serverName: [
          {
            max: 64,
            required: true,
            message: this.$t("PLACEENTER") + 64 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        appId: [
          {
            max: 64,
            required: true,
            message: this.$t("PLACEENTER") + 64 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        appSecret: [
          {
            max: 64,
            required: true,
            message: this.$t("PLACEENTER") + 64 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        isSystemConfig: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
      statusList: [], // 状态列表
      whetherCharList: [],
      // 查询的表单的配置项
      queryForm: {
        serverCode: "",
        serverName: "",
      },
      actionButtons: [
        this.hasAuth("WECHAT_OFFICIAL_ACCOUNT:EDIT") && "edit",
        this.hasAuth("WECHAT_OFFICIAL_ACCOUNT:DELETE") && "delete",
      ],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        serverCode: {
          label: () => this.$t("OFFICIAL_ACCOUNT_CODE"),
        },
        serverName: {
          label: () => this.$t("OFFICIAL_ACCOUNT_NAME"),
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "serverCode",
          title: this.$t("OFFICIAL_ACCOUNT_CODE"),
          sorter: false,
          ellipsis: true,
          minWidth: 180,
        },
        {
          dataIndex: "serverName",
          title: this.$t("OFFICIAL_ACCOUNT_NAME"),
          ellipsis: true,
          minWidth: 180,
        },
        {
          dataIndex: "appId",
          ellipsis: true,
          title: () => this.$t("DEVELOPER_ID"),
          minWidth: 180,
        },
        {
          dataIndex: "isSystemConfig",
          sorter: false,
          title: () => this.$t("BIND_TO_USE"),
          scopedSlots: { customRender: "isSystemConfig" },
          width: 120,
        },
        {
          dataIndex: "enableFlag",
          sorter: false,
          title: () => this.$t("STATUS"),
          scopedSlots: { customRender: "enableFlag" },
          width: 120,
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          sorter: false,
          title: this.$t("UPDATE_BY"),
          width: 210,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          sorter: false,
          title: this.$t("UPDATE_TIME"),
          width: 210,
        },
      ];
    },
  },
  methods: {
    beforeSearch() {
      return Promise.all([
        this.getDictByCode(`DIC:COMMON:ENABLE_FLAG`), // 启用状态
        this.getDictByCode(`DIC:COMMON:WHETHER_CHAR`), // 是否状态
      ]).then(([enableStatusRes, whetherCharRes]) => {
        this.statusList = enableStatusRes.data.data;
        this.whetherCharList = whetherCharRes.data.data;
      });
    },
    formatData(data, curItem) {
      const result = data.find((item) => item.value === curItem);
      return result ? result.label : "";
    },
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/wechat/official/account/search`, {
          params,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = parseFloat(res.data.data.total);
        });
    },
    // 新增按钮的点击
    handleAdd() {
      this.$set(this, "form", {
        id: null,
        serverCode: "",
        serverName: "",
        appId: "",
        appSecret: "",
        isSystemConfig: "N",
      });
      this.drawerVisible = true;
    },
    // 编辑按钮点击
    handleEdit(row) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/wechat/official/account/get-by-id/${row.id}`
        )
        .then((res) => {
          this.form = { ...res?.data?.data };
          this.drawerVisible = true;
        });
    },
    // 监听点击保存事件
    handleSave() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          const req = {
            ...this.form,
          };
          if (!this.form?.id) {
            this.$axios
              .post(
                `${ApiConstant.PREFIX_CORE}/api/wechat/official/account`,
                req
              )
              .then((res) => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawerVisible = false;
              });
          } else {
            this.$axios
              .put(
                `${ApiConstant.PREFIX_CORE}/api/wechat/official/account`,
                req
              )
              .then((res) => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawerVisible = false;
              });
          }
        }
      });
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        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/wechat/official/account/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.selectedRowKeys = [];
                this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
                this.$refs.MomTable?.query();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 点击表格行内的删除
    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/wechat/official/account/${row.id}`
            )
            .then((res) => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 启用、禁用
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/wechat/official/account/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 关闭弹框
    handleClose() {
      this.$refs.addForm.clearValidate();
      this.drawerVisible = false;
    },
  },
};
</script>
