<template>
  <div class="container">
    <el-form ref="form" :model="form">
      <ele-pro-table
        style="height: 100%"
        ref="table"
        :columns="columns"
        :datasource="form.datasource"
        :page-size="20"
        @columns-change="handleColumnChange"
        :cache-key="cacheKeyUrl"
        height="calc(100% - 100px)"
        :needPage="false"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="addHandler"
            v-if="$hasPermission('main:team:save')"
          >
            添加脱敏规则
          </el-button>
        </template>

        <!-- 操作列 -->
        <template v-slot:action="{ row, $index }">
          <el-popconfirm
            class="ele-action"
            title="确定要删除此信息吗？"
            @confirm="handleDelInfo($index)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>

        <template v-slot:fieldName="{ row, $index }">
          <el-form-item
            :prop="'datasource.' + $index + '.fieldName'"
            :rules="{
              required: true,
              message: '请输入脱敏字段key',
              trigger: ['blur']
            }"
          >
            <el-input v-model="row.fieldName" clearable></el-input>
          </el-form-item>
        </template>

        <template v-slot:fieldAlias="{ row, $index }">
          <el-form-item
            :prop="'datasource.' + $index + '.fieldAlias'"
            :rules="{
              required: true,
              message: '请输入脱敏字段名称',
              trigger: ['blur']
            }"
          >
            <el-input v-model="row.fieldAlias" clearable></el-input>
          </el-form-item>
        </template>

        <template v-slot:typeId="{ row, $index }">
          <el-form-item
            :prop="'datasource.' + $index + '.typeId'"
            :rules="{
              required: true,
              message: '请选择',
              trigger: ['blur', 'change']
            }"
          >
            <el-select
              v-if="typeList.length"
              v-model="row.typeId"
              collapse-tags
              filterable
              placeholder="请选择"
              style="width: 100%"
              clearable
              size="medium"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.dataName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>

        <template v-slot:roleAuthorityList="{ row, $index }">
          <el-form-item :prop="'datasource.' + $index + '.roleAuthorityList'">
            <el-select
              v-if="roleList.length"
              v-model="row.roleAuthorityList"
              multiple
          
              filterable
              placeholder="请选择"
              style="width: 100%"
              clearable
              size="medium"
            >
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>

        <template v-slot:userAuthorityList="{ row, $index }">
          <el-form-item :prop="'datasource.' + $index + '.userAuthorityList'">
            <el-select
              :ref="'userRef' + $index"
              v-if="userList.length"
              v-model="row.userAuthorityList"
              multiple
            
              filterable
              placeholder="请选择"
              style="width: 100%"
              clearable
              size="medium"
              @focus.prevent="openUserPage(row, $index)"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>

        <template v-slot:status="{ row, $index }">
          <el-form-item :prop="'datasource.' + $index + '.status'">
            <el-switch
              v-model="row.status"
              :active-text="row.status == 1 ? '启用' : '停用'"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </el-form-item>
        </template>

        <template v-slot:headerRequired="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
      </ele-pro-table>
    </el-form>

    <UserPage
      @success="userSelect"
      ref="UserPage"
      :visible.sync="userVisible"
    ></UserPage>
  </div>
</template>

<script>
  import tabMixins from '@/mixins/tableColumnsMixin';
  import UserPage from './UserPage.vue';

  import { getRolesListAPI } from '@/api/system/role';
  import { getUserPage } from '@/api/system/organization';
  import { pageDatadesensitizetype } from '@/api/system/dataDesensitization';
  export default {
    mixins: [tabMixins],
    components: { UserPage },
    props: {
      detailList: {
        type: Array,
        default: () => []
      }
    },
    watch: {
      detailList: {
        handler(newValue) {
          this.form.datasource = newValue;
        }
      }
    },
    data() {
      return {
        cacheKeyUrl: 'mainData-system-dataDesensitization',
        form: {
          datasource: []
        },
        roleList: [],
        userList: [],
        typeList: [],
        index: null,
        userVisible: false
      };
    },
    computed: {
      columns() {
        let arr = [
          {
            width: 55,
            label: '序号',
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'fieldAlias',
            slot: 'fieldAlias',
            label: '脱敏字段名称',
            width: 120,
            align: 'center',
            showOverflowTooltip: true,
            headerSlot: 'headerRequired'
          },
          {
            prop: 'fieldName',
            slot: 'fieldName',
            label: '脱敏字段key',
            width: 120,
            align: 'center',
            showOverflowTooltip: true,
            headerSlot: 'headerRequired'
          },

          {
            prop: 'typeId',
            slot: 'typeId',
            label: '脱敏规则类型',
            align: 'center',
            width: 150,
            showOverflowTooltip: true,
            headerSlot: 'headerRequired'
          },
          {
            prop: 'roleAuthorityList',
            slot: 'roleAuthorityList',
            label: '可查看角色',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'userAuthorityList',
            slot: 'userAuthorityList',
            label: '可查看账号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'status',
            slot: 'status',
            width: 120,
            label: '启用状态',
            slot: 'status',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            columnKey: 'action',
            label: '操作',
            width: 80,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ];
        return arr;
      }
    },
    methods: {
      async getRolesList() {
        const res = await getRolesListAPI();
        this.roleList = res;
      },
      async getUserList() {
        let { list } = await getUserPage({ pageNum: 1, size: -1 });
        this.userList = list;
      },
      async getTypeList() {
        let res = await pageDatadesensitizetype({
          pageNum: 1,
          size: -1
        });
        this.typeList = res.list;
      },
      addHandler() {
        this.form.datasource.push({
          fieldName: '',
          fieldAlias: '',
          typeId: '',
          roleAuthorityList: [],
          userAuthorityList: [],
          status: 1
        });
      },
      openUserPage(row, index) {
        console.log(row);
        this.index = index;
        console.log(this.$refs);
        let ref = 'userRef' + index;

        this.$refs[ref].blur();

        this.$refs.UserPage.open('1', row.userAuthorityList);

        // this.userVisible = true;
      },
      visibleType() {
        this.$nextTick(() => {
          this.$refs.userRef.blur();
        });
      },
      userSelect(e) {
        let ids = e.data.map((item) => item.id);
        console.log(this.index);
        this.$set(this.form.datasource[this.index], 'userAuthorityList', ids);

        console.log(e);
      },
      handleDelInfo(index) {
        this.form.datasource.splice(index, 1);
      },

      getTableValidate() {
        return new Promise((resolve, reject) => {
          // if (this.form.datasource.length == 0) return this.$message.warning('请添加至少一条交付物信息')
          this.$refs.form.validate((valid) => {
            if (!valid) {
              this.$message.warning('有必填项未填，请检查');
              reject('有必填项未填，请检查');
            } else {
              resolve(this.form.datasource);
            }
          });
        });
      }
    },
    created() {
      if (this.detailList.length) {
        this.form.datasource = detailList;
      }
      this.getRolesList();
      this.getUserList();
      this.getTypeList();
    }
  };
</script>

<style lang="scss" scoped>
  .container {
    width: 100%;
    height: 100%;
  }

  table th .is-required:before {
    content: '*';
    color: red;
    margin-right: 4px;
  }
</style>
