<template>
  <CommonModal
    v-model="show"
    title="复制权限"
    :width="420"
    :on-confirm="onConfirm"
    @change="onVisibleChange"
  >
    <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="['NAME']"
            :hidecolumns="['ID']"
            :default-selected="singleDefaultSelected"
            :data="singleDropDownSelectFilterData"
            @on-fkrp-selected="singleDropSelected"
            @on-page-change="singleDropPageChange"
            @on-popper-hide="singlePopperHide"
            @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="totalRowCount"
            :page-size="dropPageSize"
            :columns-key="['NAME']"
            :hidecolumns="['ID']"
            :default-selected="multipleDefaultSelected"
            :auto-data="multipleAutoData"
            :data="multipleDropDownSelectFilterData"
            @on-fkrp-selected="multipleDropSelected"
            @on-page-change="multipleDropPageChange"
            @on-popper-hide="multiplePopperHide"
            @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>
  </CommonModal>
</template>

<script>
  import CommonModal from '../commonModal/index.vue';

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

  export default {
    name: 'CopyPermissionModal',

    model: {
      prop: 'visible',
      event: 'change',
    },

    props: {
      visible: {
        type: Boolean,
      },
      triggerRefresh: {
        type: Function,
        default: () => {}
      }
    },

    components: {
      CommonModal,
    },

    watch: {
      visible(val) {
        this.show = val;

        if (val) {
          this.getCopyPermissionData();
        } else {
          this.singleDefaultSelected = [];
          this.multipleDefaultSelected = [];
          this.singleAutoData = [];
          this.multipleAutoData = [];
          this.copyType = '';
        }
      },
    },

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

    mounted() {},

    methods: {
      onVisibleChange(val) {
        this.$emit('change', val);
      },

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

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

      // 外键单选popper隐藏时触发
      singlePopperHide() {
        this.getSingleDropSelectData(1, this.backupsDropData);
      },

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

      // 外键单选输入框值改变时触发
      singleInputChange(val) {
        if (val) {
          this.singleAutoData = this.backupsDropData.reduce((acc, cur) => {
            if (cur.NAME && cur.NAME.indexOf(val) !== -1) {
              acc.push({ ID: cur.ID, NAME: cur.NAME });
            }
            return acc;
          }, []);
        } else {
          this.singleAutoData = [];
        }
      },

      // 整合复制权限外键单选数据
      getSingleDropSelectData(pageValue, data) {
        const start = (pageValue - 1) * this.dropPageSize;
        const tabth = [
          {
            colname: 'ID',
            name: 'ID',
            isak: false,
          },
          {
            colname: 'NAME',
            name: this.$t('tips.role'),
            isak: true,
          },
        ];
        const row = data
          .slice(start, start + this.dropPageSize)
          .reduce((acc, cur) => {
            const obj = {
              ID: {
                val: cur.ID,
              },
              NAME: {
                val: cur.NAME,
              },
            };
            acc.push(obj);
            return acc;
          }, []);
        this.singleDropDownSelectFilterData = {
          start,
          tabth,
          row,
        };
      },

      // 获取复制权限外键的数据
      getCopyPermissionData() {
        network.post('/p/cs/cgroupsquery', { NAME: '' }).then((res) => {
          if (res.data.code === 0) {
            this.backupsDropData = res.data.data;
            this.totalRowCount = res.data.data.length;
            this.getSingleDropSelectData(1, res.data.data);
            this.getMultipleDropSelectData(1, res.data.data);
          }
        });
      },

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

      // 外键多选popper隐藏时触发
      multiplePopperHide() {
        this.getMultipleDropSelectData(1, this.backupsDropData);
      },

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

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

      // 复制权限外键多选输入时触发
      multipleInputChange(val) {
        if (val) {
          this.multipleAutoData = this.backupsDropData.reduce((acc, cur) => {
            if (cur.NAME && cur.NAME.indexOf(val) !== -1) {
              acc.push({ ID: cur.ID, NAME: cur.NAME });
            }
            return acc;
          }, []);
        } else {
          this.multipleAutoData = [];
        }
      },

      // 整合复制权限外键多选数据
      getMultipleDropSelectData(pageValue, data) {
        const start = (pageValue - 1) * this.dropPageSize;
        const tabth = [
          {
            colname: 'ID',
            name: 'ID',
            isak: false,
          },
          {
            colname: 'NAME',
            name: this.$t('tips.role'),
            isak: true,
          },
        ];
        const row = data
          .slice(start, start + this.dropPageSize)
          .reduce((acc, cur) => {
            const obj = {
              ID: {
                val: cur.ID,
              },
              NAME: {
                val: cur.NAME,
              },
            };
            acc.push(obj);
            return acc;
          }, []);
        this.multipleDropDownSelectFilterData = {
          start,
          tabth,
          row,
        };
      },

      // 确认
      onConfirm() {
        if (this.singlePermissionId === null) {
          this.$Message.warning({
            content: '请选择原角色'
          });
          return;
        }
        if (this.multiplePermissionId === null) {
          this.$Message.warning({
            content: '请选择目标角色'
          });
          return;
        }

        const list = this.multiplePermissionId.split(',')
        if (list.includes(this.singlePermissionId.toString())) {
          this.$Message.warning({
            content: '目的角色不能包含源角色，请重新选择'
          });
          return;
        }
        if (this.copyType === '') {
          this.$Message.warning({
            content: '请选择复制方式'
          });
          return;
        }

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

        network.post('/p/cs/dataPermissionCopy', obj)
          .then((res) => {
            if (res.data.code === 0) {
              this.singlePermissionId = null;
              this.multiplePermissionId = null;
              this.triggerRefresh();
              this.$Message.success({
                content: res.data.message
              });
            }
          }).finally(() => {
            this.$emit('change', false);
          });
      }
    },
  };
</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>
