<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="18vh"
    width="900px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @close="closeModel"
  >
    <el-card>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :rules="rulesThis"
            label-width="130px"
            class="demo-ruleForm"
          >
            <el-form-item label="共享的菜单数据" prop="collect">
              <el-select
                v-model="ruleForm.collect"
                style="width: 100%"
                multiple
                filterable
                clearable
                :disabled="isDetail"
                placeholder="请选择菜单数据"
              >
                <!-- <el-option
                  v-for="item in actionList"
                  :key="`collect` + item.id"
                  :label="item.menu_name"
                  :value="item.id"
                  :disabled="item.status !== '1'"
                >
                </el-option> -->
                <el-option-group
                  v-for="(group, index) in actionList"
                  :key="group.menu_name + index"
                  :label="group.menu_name"
                >
                  <el-option
                    v-for="(item, i) in group.child"
                    :key="'item' + item.menu_name + i"
                    :label="item.menu_name"
                    :value="item.id"
                  />
                </el-option-group>
              </el-select>
            </el-form-item>

            <el-form-item label="数据源用户" prop="userid">
              <el-select
                v-model="ruleForm.userid"
                multiple
                filterable
                clearable
                :multiple-limit="1"
                placeholder="请选择数据源用户"
                :disabled="isDetail"
                style="width: 100%"
              >
                <el-option
                  v-for="item in activeOptions"
                  :key="`userid` + item.id"
                  :label="item.name"
                  :value="item.id"
                  :disabled="item.status !== '1'"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.role_name
                  }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-divider />

            <el-form-item label="数据共享对象" required>
              <ul class="dataShare-edit">
                <li>
                  <el-select
                    slot="prepend"
                    v-model="select"
                    placeholder="请选择"
                  >
                    <el-option label="用户" value="1" />
                    <el-option label="用户组" value="2" />
                  </el-select>
                </li>
                <li>
                  <el-select
                    v-if="select === '1'"
                    v-model="ruleForm.touserid"
                    multiple
                    filterable
                    :multiple-limit="1"
                    clearable
                    placeholder="请选择用户"
                    :disabled="isDetail"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in activeOptions"
                      :key="`touserid` + item.id"
                      :label="item.name"
                      :value="item.id"
                      :disabled="item.status !== '1'"
                    >
                      <span style="float: left">{{ item.name }}</span>
                      <span
                        style="float: right; color: #8492a6; font-size: 13px"
                      >{{ item.role_name }}</span>
                    </el-option>
                  </el-select>
                  <el-select
                    v-else
                    v-model="ruleForm.togroupid"
                    multiple
                    filterable
                    :multiple-limit="1"
                    clearable
                    placeholder="请选择用户组"
                    :disabled="isDetail"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in groupallList"
                      :key="`togroupid` + item.id"
                      :label="item.group_name"
                      :value="item.id"
                      :disabled="item.status !== '1'"
                    />
                  </el-select>
                </li>
              </ul>
              <!-- <el-input v-model="ruleForm.tel" :disabled="isDetail"></el-input> -->
            </el-form-item>

            <el-form-item label="共享的数据权限" prop="action">
              <el-radio v-model="ruleForm.action" label="0">只读</el-radio>
              <el-radio v-model="ruleForm.action" label="1">读写</el-radio>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button
            v-if="!isDetail"
            type="primary"
            @click="submitForm"
          >保 存
          </el-button>
          <el-button @click="showModelThis = false">{{
            isDetail ? "关 闭" : "取 消"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from '@/apis/service/interest/dataShare'

export default {
  name: 'DataShare',
  props: ['showModel', 'id', 'isDetail'],
  data() {
    return {
      loading: false,
      title: '添加共享规则',
      showModelThis: this.showModel,
      select: '1',
      activeOptions: [],
      actionList: [],
      ruleForm: {
        collect: [],
        userid: [],
        touserid: [],
        togroupid: [],
        action: '0'
        // isAdmin: 0
      },
      rulesThis: this.rules,
      rules: {
        collect: [
          { required: true, message: '请选择共享的菜单', trigger: 'change' }
        ],
        userid: [
          { required: true, message: '请选择数据源用户', trigger: 'change' }
        ],
        touserid: [
          { required: false, message: '请选择数据共享用户', trigger: 'change' }
        ],
        togroupid: [
          {
            required: false,
            message: '请选择数据共享用户组',
            trigger: 'change'
          }
        ],
        action: [
          { required: true, message: '请选择数据权限', trigger: 'change' }
        ]
      },
      dataForm: {
        name: '', // 业务员名字
        // username: "", //账号
        status: '' //
        // page: 1, // 页码
        // size: 5, // 每页显示条数
      },
      activeOptions: [],
      groupallList: []
    }
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.initForm()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
      }
    }
  },
  methods: {
    closeModel() {
      console.log('closeModel!!')
    },
    async initForm() {
      this.loading = true
      await this.initActionList()
      await this.getAllActive()
      await this.groupAllActive()
      if (this.id === 'add') {
        this.title = '添加共享规则'
        // this.ruleForm.isAdmin = 0;

        this.rulesThis = this.rules
        await this.resetForm()
      } else {
        if (this.isDetail) {
          this.title = '共享规则'
          this.rulesThis = {}
        } else {
          this.title = '修改共享规则'
          this.rulesThis = this.rules
        }
        await this.resetForm()
        await this.initData()
      }
      this.loading = false
    },
    async initData() {
      // this.loading = true;
      const res = await asyncRequest.detail({ id: this.id })
      // this.loading = false;
      if (res.code === 0) {
        const data = res.data
        this.ruleForm.collect = data.action_collect.split(',')
        this.ruleForm.userid = data.share_user.split(',')
        this.ruleForm.touserid =
          data.to_user === '' ? [] : data.to_user.split(',')
        this.ruleForm.togroupid =
          data.to_group === '' ? [] : data.to_group.split(',')
        this.ruleForm.action = data.action
        if (this.ruleForm.touserid.length !== 0) {
          this.select = '1'
        } else {
          this.select = '2'
        }
      }
      console.log(this.ruleForm)
    },
    async initActionList() {
      const res = await asyncRequest.actionList({})
      if (res.code === 0) {
        const list = res.data
        const arr = list.filter((item) => item.child && item.child.length > 0)
        this.actionList = arr
        // console.log(this.actionList);
      }
    },
    async getAllActive() {
      const res = await asyncRequest.accountall(this.dataForm)
      if (res.code === 0 && res.data) {
        this.activeOptions = res.data
      }
    },
    async groupAllActive() {
      const res = await asyncRequest.groupall(this.dataForm)
      if (res.code === 0 && res.data) {
        this.groupallList = res.data
      }
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.clearValidate()
          this.ruleForm = {
            collect: [],
            userid: [],
            touserid: [],
            togroupid: [],
            action: '0'
            // isAdmin: 0
          }
        }
      })
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          if (this.ruleForm.touserid.length === 0 && this.select === '1') {
            this.$message.warning('请选择数据共享用户')
            return
          }
          if (this.ruleForm.togroupid.length === 0 && this.select !== '1') {
            this.$message.warning('请选择数据共享用户组')
            return
          }
          this.loading = true
          const obj = JSON.parse(JSON.stringify(this.ruleForm))
          const model = {
            id: this.id,
            collect: obj.collect.join(),
            userid: obj.userid.join(),
            touserid: this.select === '1' ? obj.touserid.join() : '',
            togroupid: this.select === '1' ? '' : obj.togroupid.join(),
            action: obj.action
          }
          let res = {}
          if (this.id === 'add') {
            delete model['id']
            res = await asyncRequest.add(model)
          } else {
            res = await asyncRequest.update(model)
          }
          this.loading = false
          if (res.code === 0) {
            const title = this.id === 'add' ? '添加成功' : '修改成功'
            this.$notify.success({
              title,
              message: ''
            })
            this.showModelThis = false
            // 刷新
            this.$emit('refresh')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

   <style lang="scss" scoped>
.dataShare {
  .dataShare-edit {
    width: 100%;
    display: flex;
    li {
      &:first-child {
        width: 100px;
        position: relative;
      }
      &:last-child {
        width: calc(100% - 100px);
      }
    }
  }
}
</style>
