<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"
      :mega-extend="{
        rowAction: {
          width: 160,
        },
      }"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="searchPageData"
    >
      <a-row slot="toolbar" class="button-top-table">
        <a-button v-if="hasAuth('CODE_GENERATION:ADD')" @click="handleAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button class="btn__blue" @click="handleBatchDownload">
          <Icon type="icon-dir-f-upload" :size="15" />
          {{ $t("CORE_BATCH_DOWNLOAD") }}
        </a-button>
        <a-button
          v-if="hasAuth('CODE_GENERATION:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </a-row>
      <span slot="tablePrefix" slot-scope="text">
        {{ getAttrValue(tablePrefixList, text) }}
      </span>
      <span slot="generateType" slot-scope="text">
        {{ getAttrValue(generateTypeList, text) }}
      </span>
      <template slot="status" slot-scope="text, record">
        <span v-if="record.status == 'NORMAL'" style="color: #0fd19c">{{
          formatData(statusList, record.status)
        }}</span>
        <span v-else style="color: #d45f5f">{{
          formatData(statusList, record.status)
        }}</span>
      </template>
    </MomTable>
    <MegaDrawer
      width="520"
      :title="form.id ? $t('EDIT') : $t('ADD')"
      :visible="drawerVisible"
      @close="handleCloseDrawer"
      @cancel="handleCloseDrawer"
      @ok="handleSave"
    >
      <a-form-model
        slot="main"
        ref="addForm"
        layout="vertical"
        :model="form"
        :rules="rules"
      >
        <a-row>
          <a-col :span="24">
            <a-form-model-item :label="$t('DATA_SOURCE')" prop="dataSourceId">
              <a-select
                v-model="form.dataSourceId"
                @change="changeDataSource()"
              >
                <a-select-option
                  v-for="item in dataSourceList"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.dataSourceName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="$t('TABLE_NAME')" prop="tableName">
              <a-select
                v-model="form.tableName"
                show-search
                @change="changeTableName()"
              >
                <a-select-option
                  v-for="item in tableList"
                  :key="item.tableName"
                  :value="item.tableName"
                >
                  {{ item.tableName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item :label="$t('FUNCTION_NAME')" prop="tableComment">
              <a-input v-model="form.tableComment" />
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item :label="$t('BUSINESS_NAME')" prop="businessName">
              <a-input v-model="form.businessName" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="$t('AUTHOR_NAME')" prop="authorName">
              <a-input v-model="form.authorName" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('TABLE_PREFIX_REMOVAL')"
              prop="tablePrefix"
            >
              <a-radio-group v-model="form.tablePrefix">
                <a-radio
                  v-for="item in tablePrefixList"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.label }}</a-radio
                >
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('CODE_GENERATE_CLASS_NAME')"
              prop="className"
            >
              <a-input v-model="form.className" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              :label="$t('GRNERATION_TYPE')"
              prop="generateType"
            >
              <a-radio-group v-model="form.generateType" @change="changeType()">
                <a-radio
                  v-for="item in generateTypeList"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.label }}</a-radio
                >
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col v-if="form.generateType === '1'" :span="24">
            <a-form-model-item
              :label="$t('CODE_PACKAGE_NAME')"
              prop="packageName"
            >
              <a-input v-model="form.packageName" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </MegaDrawer>
  </div>
</template>

<script>
import { uniqBy } from "lodash";
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, // 新增修改的弹框
      drawerVisibleView: false, // 查看弹框
      // 查询sort
      tableData: [], // 表格数据
      page: 1, // 分页第几页
      total: 0, // 数据表格总条数
      isQuery: true,
      form: {
        id: "",
        dataSourceId: "", // 数据源名称
        tableName: "", // 表名称
        tableComment: "", // 功能名
        businessName: "", // 业务名
        authorName: "", // 作者姓名
        tablePrefix: "", // 表前缀移除
        className: "", // 类名
        generateType: "", // 生成方式
        packageName: "", // 代码包名
      },
      rules: {
        dataSourceId: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        tableName: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        tableComment: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        businessName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        authorName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        tablePrefix: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        className: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        generateType: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        packageName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
      dataSourceList: [], // 数据源列表
      tableList: [], // 表列表
      statusList: [], // 状态列表
      tablePrefixList: [], // 表前缀移除列表
      generateTypeList: [], // 生成类型列表
      tableNameValue: "",
      // 查询的表单的配置项
      queryForm: {
        dataSourceId: "",
        tableName: "",
      },
      actionButtons: [
        (h, { record }) => (
          <span
            class="text-primary cursor-pointer"
            title={this.$t("VIEW")}
            onClick={() => this.handleView(record)}>
            <Icon class="operation-icon mt-3" type="icon-cur-eye" size={14} />
          </span>
        ),
        (h, { record }) => (
          <span
            class="text-primary cursor-pointer"
            title={this.$t("START_BUILD")}
            onClick={() => this.runDownCodeGenerate(record)}>
            <Icon type="icon-cur-handle" class="mt-3" size={14} />
          </span>
        ),
        (h, { record }) => (
          <span
            class="text-primary cursor-pointer"
            title={this.$t("CONFIG")}
            onClick={() => this.handleConfig(record)}>
            <Icon type="icon-data-sliders" class="mt-3" size={14} />
          </span>
        ),
        this.hasAuth("CODE_GENERATION:EDIT") && "edit",
        this.hasAuth("CODE_GENERATION:DELETE") && "delete",
      ],
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
    };
  },
  computed: {
    queryFormItem() {
      return this.$observable("queryFormItem", {
        dataSourceId: {
          itemType: "select",
          label: () => this.$t("DATA_SOURCE"),
          labelWidth: 60,
          options: [],
          optionsProps: {
            label: "dataSourceName",
            value: "id",
          },
          on: {
            change: () => {
              this.isQuery = true;
              setTimeout(() => {
                this.getAllTable();
              }, 500);
            },
          },
        },
        tableName: {
          itemType: "select",
          label: () => this.$t("TABLE_NAME"),
          labelWidth: 60,
          options: [],
          optionsProps: {
            label: "tableName",
            value: "tableName",
          },
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "dataSourceName",
          title: this.$t("DATA_SOURCE"),
          ellipsis: true,
          width: 150,
        },
        {
          dataIndex: "tableName",
          title: this.$t("TABLE_NAME"),
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "packageName",
          title: this.$t("CODE_PACKAGE_NAME"),
          ellipsis: true,
          width: 200,
        },

        {
          dataIndex: "businessName",
          title: this.$t("BUSINESS_NAME"),
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "className",
          title: this.$t("CODE_GENERATE_CLASS_NAME"),
          ellipsis: true,
          minWidth: 200,
        },
        {
          dataIndex: "tableComment",
          title: this.$t("FUNCTION_NAME"),
          ellipsis: true,
          width: 150,
        },
        {
          dataIndex: "authorName",
          title: this.$t("AUTHOR_NAME"),
          ellipsis: true,
          minWidth: 150,
        },
        {
          dataIndex: "tablePrefix",
          align: "left",
          title: this.$t("TABLE_PREFIX_REMOVAL"),
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: "tablePrefix" },
        },
        {
          dataIndex: "generateType",
          align: "left",
          width: 150,
          ellipsis: true,
          title: () => this.$t("GRNERATION_TYPE"), // 类型
          scopedSlots: { customRender: "generateType" },
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          title: this.$t("UPDATE_BY"),
          width: 150,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          title: this.$t("UPDATE_TIME"),
          width: 210,
        },
      ];
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
          if (this.selectedRowKeys.length) {
            this.selectedRows = uniqBy(this.selectedRows.concat(selectedRows));
          } else {
            this.selectedRows = selectedRows;
          }
        },
      };
    },
  },
  mounted() {
    this.getAllDatasource();
    this.queryDictData();
  },
  methods: {
    // 获所有数据源
    getAllDatasource() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource/list`, {})
        .then((res) => {
          this.queryFormItem.dataSourceId.options = res.data.data;
          this.dataSourceList = res.data.data;
        });
    },
    // 获取所有表
    getAllTable() {
      this.queryForm.tableName = "";
      const params = {
        dataSourceId:
          this.isQuery === true
            ? this.queryForm.dataSourceId
            : this.form.dataSourceId,
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource-query/list-table`, {
          params,
        })
        .then((res) => {
          this.queryFormItem.tableName.options = res.data.data;
          this.tableList = res.data.data;
        });
    },
    queryDictData() {
      return Promise.all([
        this.getDictByCode(`DIC:COMMON:ENABLE_STATUS`), // 启用状态
        this.getDictByCode(`CODEGENERATE:GEN_TYPE`), // 生成方式
        this.getDictByCode(`DIC:COMMON:WHETHER_CHAR`), // 是否
      ]).then(([enableStatusRes, typeRes, whetherRes]) => {
        this.statusList = enableStatusRes.data.data;
        this.generateTypeList = typeRes.data.data;
        this.tablePrefixList = whetherRes.data.data;
      });
    },
    // 切换数据源
    changeDataSource() {
      this.getAllTable();
    },
    // 切换表名
    changeTableName() {
      const index = this.tableList.findIndex(
        (item) => item.tableName === this.form.tableName
      );
      const tableName = this.classNameToHump();
      this.form.tableComment = this.tableList[index].tableComment;
      this.form.businessName = tableName.toLowerCase();
      this.form.className = tableName;
    },
    // 切换类型
    changeType() {
      this.rules.packageName[0].required = this.form.generateType === "1";
    },
    /**
     * 设置类名为数据库表的驼峰命名
     */
    classNameToHump() {
      const arr = this.form.tableName.toLowerCase().split("_");
      if (this.tablePrefixValue === "Y") {
        arr.splice(0, 1);
      }
      for (let i = 0; i < arr.length; i += 1) {
        // charAt()方法得到第一个字母，slice()得到第二个字母以后的字符串
        arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
      }
      return arr.join("");
    },
    formatData(data, curItem) {
      const result = data.find((item) => item.value === curItem);
      return result ? result.label : "";
    },
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/dev/code-generate/search`, {
          params,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = parseFloat(res.data.data.total);
        });
    },
    // 新增按钮的点击
    handleAdd() {
      this.$set(this, "form", {
        id: "",
        dataSourceId: this.queryForm.dataSourceId || "",
        tableName: "", // 表名称
        tableComment: "", // 功能名
        businessName: "", // 业务名
        authorName: "", // 作者姓名
        tablePrefix: "N", // 表前缀移除
        className: "", // 类名
        generateType: "1", // 生成方式
        packageName: "com.mega", // 代码包名
      });
      this.isQuery = false;
      this.drawerVisible = true;
    },
    // 编辑按钮点击
    handleEdit(row) {
      this.form = { ...row };
      setTimeout(() => {
        this.getAllTable();
      }, 500);
      this.isQuery = false;
      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/dev/code-generate`, req)
              .then((res) => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawerVisible = false;
                this.isQuery = true;
              });
          } else {
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/dev/code-generate`, req)
              .then((res) => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawerVisible = false;
                this.isQuery = true;
              });
          }
        }
      });
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            this.$axios
              .delete(
                `${ApiConstant.PREFIX_CORE}/api/dev/code-generate/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$message.success(this.$t("DELETE_SUCCESS"));
                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"),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(
              `${ApiConstant.PREFIX_CORE}/api/dev/code-generate/${row.id}`
            )
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 批量下载
    handleBatchDownload() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning(this.$t("SELECT_ONE_DATA"));
        return;
      }
      const ids = this.selectedRowKeys;
      this.$confirm({
        title: this.$t("TIPS"),
        content: this.$t("CONFIRM_DOWNLOAD_INFO"),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          window.open(
            `${ApiConstant.PREFIX_CORE}/api/dev/code-generate/run-down-batch?ids=${ids}`
          );
        },
      });
    },
    // 代码预览
    handleView({ id }) {
      this.$router.push({
        path: "/codegenerate/preview",
        query: {
          id,
        },
      });
    },
    /**
     * 开始生成代码（生成压缩包）
     */
    runDownCodeGenerate(record) {
      this.$confirm({
        title: this.$t("TIPS"),
        content:
          record.generateType === "1"
            ? this.$t("CONFIRM_DOWNLOAD_INFO")
            : this.$t("CONFIRM_INFO"),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          if (record.generateType === "1") {
            window.open(
              `${ApiConstant.PREFIX_CORE}/api/dev/code-generate/run-down/${record.id}`
            );
          } else {
            this.$axios
              .post(
                `${ApiConstant.PREFIX_CORE}/api/dev/code-generate/run-local/${record.id}`
              )
              .then((res) => {
                this.$message.success(this.$t("GENERATED_SUCCESS"));
                this.$refs.MomTable?.query();
              });
          }
        },
      });
    },
    // 配置
    handleConfig({ id }) {
      this.$router.push({
        path: "/codegenerate/config",
        query: {
          id,
        },
      });
    },
    // 关闭弹框
    handleCloseDrawer() {
      this.$refs.addForm.clearValidate();
      this.drawerVisible = false;
    },
  },
};
</script>
