<template>
  <div>
    <a-button
      v-if="hasAuth('EPMS:EQUIPMENT:FIELD_AUTH')"
      style="margin-right: 8px"
      type="primary"
      :class="{ 'show-red-border': showRedBorder === true }"
      @click="hanldeFieldAuth()"
    >
      <i class="iconfont icon-tianjia"></i>
      {{ $t("PFM4010") }}
    </a-button>
    <MegaDrawer
      width="1000"
      :title="`${$t('PFM4010')}`"
      :visible="drawerVisible"
      @close="drawerVisible = false"
      @cancel="handleCancel"
      @ok="handleSave"
    >
      <a-form-model slot="main" ref="formAuth" :model="formAuth">
        <a-tabs v-model="activeKeyAuth">
          <a-tab-pane
            v-for="(table, tableIndex) in formAuth.tableList"
            :key="table.tableName"
            :tab="table.tableComment"
          >
            <MomTable
              ref="TableInfo"
              :visible="infoTableVisible"
              :row-key="rowKeySet"
              :columns="infoColumns"
              :data-source="table.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'"
                  @change="onChangeFlag($event, record, tableIndex)"
                />
              </span>
            </MomTable>
          </a-tab-pane>
        </a-tabs>
      </a-form-model>
    </MegaDrawer>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import FieldExtendMixin from "@/mixins/fieldExtend";

export default {
  name: "",
  components: {
    MegaDrawer,
  },
  mixins: [FieldExtendMixin],
  props: {
    formData: {
      type: Object,
      default() {
        return {};
      },
    },
    tableNameList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      fieldNames: { label: "label", value: "code", children: "children" },
      form: {},
      activeKeyAuth: "",
      drawerVisible: false,
      infoTableVisible: false,
      yesNoList: [],
      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: [],
      },
    };
  },
  computed: {
    ...mapState({
      showRedBorder: (state) => state.pagination.showRedBorder,
    }),
  },
  mounted() {
    // this.init();
  },
  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.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 = true;
    },
    // 开关
    onChangeFlag(e, data, tableIndex) {
      // 获取表单下的数据
      this.formAuth.tableList[tableIndex].fieldList.forEach((item, index) => {
        if (item.fieldName === data.fieldName) {
          this.formAuth.tableList[tableIndex].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.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;
    },
  },
};
</script>
