<template>
  <div>
    <MomTable
      ref="TableList"
      row-key="id"
      :query-param="queryParam"
      :query-param-item="queryParamItem"
      :columns="columns"
      :data-source="dataSource"
      :total="total"
      :page.sync="page"
      :action-buttons="['edit']"
      @search="search"
      @edit="handleEdit"
      @delete="handleDelete"
    >
      <!-- <div slot="toolbar" class="button-top-table">
        <a-button @click="handleAdd">
          <a-icon type="plus" />
          {{ $t("ADD") }}
        </a-button>
      </div> -->
    </MomTable>
    <MegaDrawer
      width="1000"
      :title="drawerTitle"
      :visible="drawerVisible"
      @close="drawerVisible = false"
      @cancel="handleCancel"
      @ok="handleSave"
    >
      <a-form-model
        slot="main"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-form-model-item
          :label="`${$t('JSON_BUILD_TABLE')}${$t('NAME')}`"
          prop="tableName"
        >
          <a-select
            v-model="form.tableName"
            :placeholder="$t('PLACESELECT')"
            @change="handleChangeTableName"
          >
            <a-select-option
              v-for="item in tableList"
              :key="item.tableName"
              :value="item.tableName"
              >{{ item.tableComment }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <MomTable
          ref="TableInfo"
          :visible="infoTableVisible"
          :row-key="rowKeySet"
          :columns="infoColumns"
          :data-source="infoDataSource"
          :show-util-operator="false"
          :pagination="false"
          :mega-extend="{
            rowAction: false,
          }"
        >
          <span slot="moduleCodeList" slot-scope="item, record">
            <a-select
              v-if="momTableShow"
              mode="multiple"
              style="width: 100%"
              :data-key="form.tableName"
              :default-value="item ? item : []"
              @change="handleChange($event, record)"
            >
              <a-select-option
                v-for="itemA in modules"
                :key="itemA.code"
                :value="itemA.code"
                >{{ $t(itemA.menuName) }}</a-select-option
              >
            </a-select>
          </span>
          <span slot="i18nCode" slot-scope="item">{{ $t(item) }}</span>
          <span slot="enableFlag" slot-scope="item, record">
            <a-switch
              :default-checked="item === 'Y'"
              @change="onChangeFlag($event, record)"
            />
          </span>
        </MomTable>
      </a-form-model>
    </MegaDrawer>
  </div>
</template>

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

export default {
  components: { MegaDrawer },
  data() {
    return {
      // 查询的表单的配置项
      drawerTitle: this.$t("ADD"),
      queryParam: {
        tableName: "",
      },
      columns: [
        {
          dataIndex: "tableName", // 表名
          sorter: false,
          title: () => `${this.$t("JSON_BUILD_TABLE")}${this.$t("NAME")}`,
        },
        {
          dataIndex: "tableComment", // 表说明
          sorter: false,
          title: () => `${this.$t("JSON_BUILD_TABLE")}${this.$t("DESCRIBE")}`,
        },
      ],
      infoColumns: [
        {
          dataIndex: "fieldName", // 字段名
          sorter: false,
          title: () => `${this.$t("FIELD")}${this.$t("NAME")}`,
        },
        {
          dataIndex: "i18nCode", // 国际化
          sorter: false,
          title: () => `${this.$t("I18N")}`,
          scopedSlots: { customRender: "i18nCode" },
        },
        // {
        //   dataIndex: "fieldComment", // 字段说明
        //   sorter: false,
        //   title: () => `${this.$t("FIELD")}${this.$t("DESCRIBE")}`,
        // },
        {
          dataIndex: "enableFlag", // 是否显示
          sorter: false,
          title: () => this.$t("IS_SHOW"),
          scopedSlots: { customRender: "enableFlag" },
          width: 120,
        },
        {
          dataIndex: "moduleCodeList", // 设置
          sorter: false,
          title: () => this.$t("SETTING"),
          scopedSlots: { customRender: "moduleCodeList" },
          minWidth: 300,
        },
      ],
      total: 0,
      page: 1,
      tablePage: 1,
      tableTotal: 0,
      dataSource: [],
      momTableShow: true,
      infoDataSource: [],
      drawerVisible: false,
      infoTableVisible: false,
      tableList: [],
      moduleList: [],
      form: {
        id: null,
        tableName: "",
      },
    };
  },
  computed: {
    ...mapGetters(["modules"]),
    rules() {
      return {
        tableName: [
          {
            required: true,
            max: 32,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        tableName: {
          itemType: "input",
          label: `${this.$t("JSON_BUILD_TABLE")}${this.$t("NAME")}`, // 表名称
        },
      });
    },
  },
  created() {
    this.getTableList();
    // this.getSystemModule();
  },
  methods: {
    // 设置rowkey
    rowKeySet(record) {
      return `${this.form.tableName} ${record.fieldName}`;
    },
    // 获取当前系统数据库的所有表
    getTableList() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/field-visible/list-table`)
        .then((res) => {
          this.tableList = res.data.data;
        });
    },
    // 获取系统
    getSystemModule() {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/menu/list-user-module-menu-tree`
        )
        .then((res) => {
          this.moduleList = res.data.data;
        });
    },
    search(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/field-visible/search`, {
          params,
        })
        .then((res) => {
          this.dataSource = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 开关
    onChangeFlag(e, data) {
      // 获取表单下的数据
      this.fieldList.forEach((item, index) => {
        if (item.fieldName === data.fieldName) {
          this.fieldList[index].enableFlag = e ? "Y" : "N";
        }
      });
    },
    // 选择表名称
    handleChangeTableName(tableName) {
      this.momTableShow = false;
      // 获取表单下的数据
      const tableData = this.tableList
        .filter((item) => item.tableName === tableName)
        .shift();
      this.form.tableComment = tableData ? tableData.tableComment : "";
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/field-visible/list-column`, {
          params: { tableName },
        })
        .then((res) => {
          this.infoTableVisible = true;
          this.infoDataSource = res.data.data;
          this.fieldList = this.infoDataSource;
          this.momTableShow = true;
        });
    },
    // 选择设置
    handleChange(e, colitem) {
      // 获取表单下的数据
      this.fieldList.forEach((item, index) => {
        if (item.fieldName === colitem.fieldName) {
          this.fieldList[index].moduleCodeList = e;
        }
      });
    },
    handleEdit({ id, tableName, tableComment }) {
      this.drawerTitle = this.$t("EDIT");
      this.form.id = id;
      this.form.tableName = tableName;
      this.form.tableComment = tableComment;
      this.drawerVisible = true;
      this.handleChangeTableName(this.form.tableName);
    },
    handleAdd() {
      this.drawerTitle = this.$t("ADD");
      this.form.id = null;
      this.form.tableName = "";
      this.form.tableComment = "";
      this.infoDataSource = [];
      this.fieldList = [];
      this.drawerVisible = true;
    },
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "danger",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(
              `${ApiConstant.PREFIX_CORE}/api/sys/field-visible/${row.id}`
            )
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.TableList?.query();
            });
        },
      });
    },
    handleSave() {
      if (this.form.id) {
        this.$axios
          .put(`${ApiConstant.PREFIX_CORE}/api/sys/field-visible`, {
            fieldList: this.fieldList,
            ...this.form,
          })
          .then(() => {
            this.$message.success(this.$t("EDIT_SUCCESS"));
            this.$refs.TableList?.query();
            this.drawerVisible = false;
          });
      } else {
        this.$axios
          .post(`${ApiConstant.PREFIX_CORE}/api/sys/field-visible`, {
            fieldList: this.fieldList,
            ...this.form,
          })
          .then(() => {
            this.$message.success(this.$t("EDIT_SUCCESS"));
            this.$refs.TableList?.query();
            this.drawerVisible = false;
          });
      }
    },
    handleCancel() {
      this.drawerVisible = false;
    },
  },
};
</script>
