<template>
  <div>
    <MomTable
      ref="TableInfo"
      :visible="infoTableVisible"
      :row-key="rowKeySet"
      :columns="infoColumns"
      :data-source="fieldList"
      :show-util-operator="false"
      :pagination="false"
      :mega-extend="{
        rowAction: false,
      }"
    >
      <span slot="i18nCode" slot-scope="item">{{ $t(item) }}</span>
      <span slot="enableFlag" slot-scope="item, record">
        <a-switch
          :checked="item === 'Y'"
          :disabled="!isEdit"
          @change="onChangeFlag($event, record)"
        />
      </span>
    </MomTable>
    <div class="page-bottom-op" :style="{ left: sideMenuWidth }">
      <a-button v-if="isEdit" type="primary" @click="handleSave()">
        <i class="iconfont icon-baocun"></i>
        {{ $t("SAVE") }}
      </a-button>
      <a-button v-if="isEdit" @click="handleCancel">
        <i class="iconfont icon-quxiao"></i>
        {{ $t("CANCEL") }}
      </a-button>
      <a-button v-if="!isEdit" type="primary" @click="handleEdit">
        <i class="iconfont icon-baocun"></i>
        {{ $t("EDIT") }}
      </a-button>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import ApiConstant from "@/api/ApiConstant";
import FieldExtendMixin from "@/mixins/fieldExtend";

export default {
  name: "",
  mixins: [FieldExtendMixin],
  props: {
    formData: {
      type: Object,
      default() {
        return {};
      },
    },
    tableNameList: {
      type: Array,
      default() {
        return [];
      },
    },
    tableNameKey: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      isEdit: false,
      fieldNames: { label: "label", value: "code", children: "children" },
      form: {},
      fieldList: [],
      activeKeyAuth: "",
      drawerVisible: false,
      infoTableVisible: false,
      yesNoList: [],
      activeTabKey: "",
      infoDataSource: [],
      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,
        },
      ],
      formAuth: {
        tableList: [],
      },
      sideMenuWidth: 0,
    };
  },
  computed: {
    ...mapState({
      showRedBorder: (state) => state.pagination.showRedBorder,
    }),
    ...mapState("setting", ["sideMenuDefaultWidth"]),
  },
  watch: {
    tableNameKey: {
      handler(newVal, oldVal) {
        this.activeTabKey = newVal;
        this.hanldeFieldAuth();
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.sideMenuWidth =
      localStorage.getItem("APP_SIDE_MENU_WIDTH") || this.sideMenuDefaultWidth;
    this.activeTabKey = this.tableNameKey;
    this.hanldeFieldAuth();
  },
  methods: {
    init() {
      // 扩展字段
      this.queryFieldExtend().then((res) => {
        /* eslint-disable */
        this.form = JSON.parse(JSON.stringify(this.formData));
        if (res.data.data.fieldHiddenConfigList?.length) {
          const arr = [];
          res.data.data.fieldHiddenConfigList.forEach((item) => {
            arr.push(item.fieldName);
          });
          arr.forEach((item) => {
            this.hasFunction(this.form, item);
          });
        }
        this.$emit("formBack", this.form);
        /* eslint-enable */
      });
    },
    // 字段授权
    hanldeFieldAuth() {
      const params = {
        tableNameList: this.activeTabKey,
        moduleCode: this.$store.state.activatedModule,
      };
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/field-visible/list-column-batch-by-module`,
          {
            params,
          }
        )
        .then((res) => {
          if (res?.data?.data && res?.data?.data.length > 0) {
            this.activeKeyAuth = res.data.data[0].tableName;
            this.fieldList = res.data.data[0].fieldList;
            this.formAuth.tableList = res.data.data;
          }
        });
      this.drawerVisible = true;
    },
    // 开关
    onChangeFlag(e, data) {
      // 获取表单下的数据
      this.fieldList.forEach((item, index) => {
        if (item.fieldName === data.fieldName) {
          this.fieldList[index].enableFlag = e ? "Y" : "N";
        }
      });
    },
    // 设置rowkey
    rowKeySet(record) {
      return `${this.form.tableName} ${record.fieldName}`;
    },
    hasFunction(obj, val) {
      // eslint-disable-next-line no-prototype-builtins
      if (obj.hasOwnProperty(val)) {
        delete this.form[val];
        delete this.fieldExForm[val];
      }
    },
    // 字段授权 保存
    handleSave() {
      const { tableList } = this.formAuth;
      const data = {
        moduleCode: this.$store.state.activatedModule,
        paramList: tableList,
      };
      this.$axios
        .post(
          `${ApiConstant.PREFIX_CORE}/api/sys/field-visible/save-batch-by-module`,
          data
        )
        .then(() => {
          this.$message.success(this.$t("EDIT_SUCCESS"));
          this.drawerVisible = false;
          this.isEdit = false;
          this.init();
        });
    },
    // 字段扩展刷新
    handleRefresh() {
      this.fieldExForm = {};
      this.queryFieldExtend();
    },
    // 字段授权弹框 取消
    handleCancel() {
      // const params = {
      //   tableNameList: this.tableNameList[0]?.key,
      //   moduleCode: this.$store.state.activatedModule,
      // };
      // this.$axios
      //   .get(
      //     `${ApiConstant.PREFIX_CORE}/api/sys/field-visible/list-column-batch-by-module`,
      //     {
      //       params,
      //     }
      //   )
      //   .then((res) => {
      //     if (res?.data?.data && res?.data?.data.length > 0) {
      //       this.activeKeyAuth = res.data.data[0].tableName;
      //       this.formAuth.tableList = res.data.data;
      //     }
      //   });
      // this.drawerVisible = false;
      this.isEdit = false;
      this.init();
      this.hanldeFieldAuth();
    },
    handleEdit() {
      this.isEdit = true;
    },
  },
};
</script>
