<template>
  <div class="copy-permission">
    <div class="modal-form">
      <div class="form-item">
        <div class="label">
          <span>原用户：</span>
        </div>
        <div class="form-item-value-panel">
          <DropDownSelectFilter
            class="itemCom"
            :total-row-count="totalRowCount"
            :page-size="dropPageSize"
            :auto-data="singleAutoData"
            :columns-key="['ENAME']"
            :hidecolumns="['ID']"
            :default-selected="singleDefaultSelected"
            :data="singleDropDownSelectFilterData"
            @on-fkrp-selected="singleDropSelected"
            @on-page-change="singleDropPageChange"
            @on-popper-show="singlePopperShow"
            @on-clear="singleDropClear"
            @on-input-value-change="singleInputChange"
          />
        </div>
      </div>
      <div class="form-item">
        <div class="label">
          <span>目标用户：</span>
        </div>
        <div class="form-item-value-panel">
          <DropDownSelectFilter
            :single="false"
            class="itemCom"
            :total-row-count="targetTotalRowCount"
            :page-size="dropPageSize"
            :columns-key="['ENAME']"
            :hidecolumns="['ID']"
            :default-selected="multipleDefaultSelected"
            :auto-data="multipleAutoData"
            :data="multipleDropDownSelectFilterData"
            @on-fkrp-selected="multipleDropSelected"
            @on-page-change="multipleDropPageChange"
            @on-popper-show="multiplePopperShow"
            @on-clear="multipleDropClear"
            @on-input-value-change="multipleInputChange"
          />
        </div>
      </div>
      <div class="form-item">
        <div class="label">
          <span>复制方式：</span>
        </div>
        <div class="form-item-value-panel">
          <Select
            v-model="copyType"
            class="itemCom"
            placeholder="请选择复制方式"
          >
            <Option value="0">
              覆盖原有角色
            </Option>
            <Option value="1">
              保留原有角色
            </Option>
          </Select>
        </div>
      </div>
    </div>

    <DialogFooter
      :on-confirm="onConfirm"
      :on-cancel="onCancel"
    />

  </div>
</template>

<script>
import DialogFooter from '../commonModal/dialog-footer.vue';

const R3 = window.R3;
const { network, urlSearchParams } = R3;

export default {
  name: 'CopyPermission',

  components: {
    DialogFooter
  },


  data() {
    return {
      // 原用户组件
      totalRowCount: 0, // 复制权限外键数据的totalRowCount
      dropPageSize: 10, // 复制权限外键数据的pageSize
      singleDefaultSelected: [], // 复制权限单选默认数据
      singlePermissionId: null, // 复制权限外键单选id
      backupsDropData: [], // 备份复制权限外键数据
      singleAutoData: [], // 复制权限外键单选模糊搜索数据
      singleDropDownSelectFilterData: {}, // 复制权限外键单选数据
      // 目标用户
      targetTotalRowCount: 0,
      multipleDefaultSelected: [], // 复制权限多选默认数据
      multipleAutoData: [], // 复制权限外键多选模糊搜索数据
      multipleDropDownSelectFilterData: {}, // 复制权限外键多选数据
      multiplePermissionId: null, // 复制权限外键多选id
      // 复制方式
      copyType: 'cover', // 复制权限弹框  复制方式
    };
  },

  mounted() {

  },

  methods: {
    close() {
      this.$emit('closeActionDialog', false);
    },

    onCancel() {
      this.close();
    },

    // 外键单选，选中触发
    singleDropSelected(val) {
      this.singlePermissionId = val[0].ID;
    },

    // 外键单选分页改变触发
    singleDropPageChange(val) {
      this.getSingleDropSelectData(val);
    },

    // 外键单选popper打开时触发
    singlePopperShow() {
      this.getSingleDropSelectData(1);
    },

    // 单选清空时触发
    singleDropClear() {
      this.singlePermissionId = null;
    },

    // 外键单选输入框值改变时触发
    async singleInputChange(value) {
      if (value === '') {
        this.singleAutoData = [];
        return;
      }

      const searchdata = {
        table: 'USERS',
        startindex: 0,
        range: 10,
        fixedcolumns: {
          ENAME: value,
          ISACTIVE: 'Y'
        },
        column_include_uicontroller: true,
        isolr: false,
        isfresh: true
      };

      const res = await this.getKeyList(searchdata)
      this.singleAutoData = res.row.map((keyObj) => {
        Object.keys(keyObj).forEach((key) => {
          keyObj[key] = keyObj[key].val;
        });
        return keyObj;
      })
      this.totalRowCount = res.totalRowCount
    },

    // 整合复制权限外键单选数据
    async getSingleDropSelectData(pageValue, data) {
      const start = (pageValue - 1) * this.dropPageSize;

      const searchdata = {
        table: 'USERS',
        startindex: start,
        range: 10,
        fixedcolumns: {
          ISACTIVE: 'Y'
        },
        column_include_uicontroller: true,
        isolr: false,
        isfresh: true
      };
      const res = await this.getKeyList(searchdata)
      this.singleDropDownSelectFilterData = res
      this.totalRowCount = res.totalRowCount
    },

    // 请求接口
    async getKeyList(searchdata) {
      return new Promise((resolve) => {
        const api = '/p/cs/QueryList';
        const result = this.commonApi(api, { searchdata }, {
          displayKeys: ['ENAME'],
        });
        resolve(result);
      });
    },

    commonApi(api, searchdata, options) {
      const { displayKeys } = options;
      return new Promise((resolve) => {
        network
          .post(api, urlSearchParams(searchdata))
          .then((res) => {
            if (res.data.code === 0) {
              const tabth = res.data.data.tabth;
              const row = res.data.data.row;

              let hideColumns = res.data.data.tabth.filter(column => !['ECODE', 'ENAME', 'NAME', 'ID'].includes(column.colname)).map(item => item.colname); // 计算隐藏列

              for (let i = Math.max(tabth.length - 1, 0); i >= 0; i--) {
                const item = tabth[i];
                // 让输入框显示 表名称 字段
                if (displayKeys.includes(item.colname)) {
                  item.isak = true;
                } else {
                  item.isak = false;
                }

                // 隐藏table列
                if (hideColumns.includes(item.colname)) {
                  tabth.splice(i, 1);
                }
              }

              if (hideColumns.length > 0) {
                row.forEach((item) => {
                  for (const key in item) {
                    // 隐藏模糊结果列
                    if (hideColumns.includes(key)) {
                      delete item[key];
                    }
                  }
                });
              }
              resolve(res.data.data);
            } else {
              resolve({});
            }
          }).catch(() => {
            resolve({});
          });
      });
    },

    // 外键多选，选中触发
    multipleDropSelected(val) {
      this.multiplePermissionId = val
        .reduce((acc, cur) => {
          acc.push(cur.ID);
          return acc;
        }, []);
    },

    // 外键多选popper打开时触发
    multiplePopperShow() {
      this.getMultipleDropSelectData(1);
    },

    // 外键多选分页改变触发
    multipleDropPageChange(val) {
      this.getMultipleDropSelectData(val);
    },

    // 多选清空时触发
    multipleDropClear() {
      this.multiplePermissionId = null;
    },

    // 复制权限外键多选输入时触发
    async multipleInputChange(value) {
      if (value === '') {
        this.singleAutoData = [];
        return;
      }

      const searchdata = {
        table: 'USERS',
        startindex: 0,
        range: 10,
        fixedcolumns: {
          ENAME: value,
          ISACTIVE: 'Y'
        },
        column_include_uicontroller: true,
        isolr: false,
        isfresh: true
      };

      const res = await this.getKeyList(searchdata)
      this.multipleAutoData = res.row.map((keyObj) => {
        Object.keys(keyObj).forEach((key) => {
          keyObj[key] = keyObj[key].val;
        });
        return keyObj;
      })
      this.targetTotalRowCount = res.totalRowCount
    },

    // 整合复制权限外键多选数据
    async getMultipleDropSelectData(pageValue, data) {
      const start = (pageValue - 1) * this.dropPageSize;

      const searchdata = {
        table: 'USERS',
        startindex: start,
        range: 10,
        fixedcolumns: {
          ISACTIVE: 'Y'
        },
        column_include_uicontroller: true,
        isolr: false,
        isfresh: true
      };
      const res = await this.getKeyList(searchdata)
      this.multipleDropDownSelectFilterData = res
      this.targetTotalRowCount = res.totalRowCount
    },

    // 确认
    onConfirm() {
      if (this.singlePermissionId === null) {
        this.$Message.warning({
          content: '请选择原用户'
        });
        return;
      }
      if (this.multiplePermissionId === null) {
        this.$Message.warning({
          content: '请选择目标用户'
        });
        return;
      }
      if (this.multiplePermissionId.indexOf(this.singlePermissionId.toString()) !== -1) {
        this.$Message.warning({
          content: '目标用户不能包含原用户，请重新选择'
        });
        return;
      }
      if (this.copyType === '') {
        this.$Message.warning({
          content: '请选择复制方式'
        });
        return;
      }

      const obj = {
        fromUserId: this.singlePermissionId,
        forUserIds: this.multiplePermissionId,
        type: Number(this.copyType)
      };

      network.post('/p/cs/larkusers/groupUserCopy', obj)
        .then((res) => {
          if (res.data.code === 0) {
            this.$Message.success({
              content: res.data.message || '复制成功'
            });
            this.close()
          }
        })
    }
  },
};
</script>

<style lang="less" scoped>
.modal-form {
  padding: 0;
  .form-item {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
    > .label {
      width: 62px;
      text-align: right;
      span {
        position: relative;
      }
      span::before {
        position: absolute;
        content: '*';
        font-size: 16px;
        color: red;
        left: -10px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
    .form-item-value-panel {
      width: 200px;
    }
  }
}
</style>
