<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="handleCloseModal"
  >
    <el-card>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-width="130px"
            class="demo-ruleForm"
          >
            <el-form-item label="共享的菜单数据" prop="menu_ids">
              <el-select
                v-model="ruleForm.menu_ids"
                style="width: 100%"
                multiple
                filterable
                clearable
                :disabled="isDetail"
                placeholder="请选择菜单数据"
              >
                <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="数据源共享对象" required>
              <ul class="dataShare-edit">
                <el-select
                  slot="prepend"
                  v-model="sourceType"
                  placeholder="请选择"
                  style="width: 120px"
                  :disabled="isDetail"
                >
                  <el-option label="用户" value="1" />
                  <el-option label="用户组" value="2" />
                </el-select>

                <!-- :disabled="item.status !== '1'" -->
                <el-select
                  v-if="sourceType === '1'"
                  v-model="ruleForm.source_uid"
                  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.nickname"
                    :value="item.id"
                  >
                    <span style="float: left">{{ item.nickname }}</span>
                    <span
                      style="
                      float: right;
                      color: #8492a6;
                      font-size: 13px;
                      padding: 0 25px 0 0;
                    "
                    >{{ item.role_name }}</span>
                  </el-option>
                </el-select>

                <el-select
                  v-else
                  v-model="ruleForm.source_data_group_id"
                  multiple
                  filterable
                  clearable
                  :multiple-limit="1"
                  placeholder="请选择数据源用户组"
                  :disabled="isDetail"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in groupallList"
                    :key="`togroupid` + item.id"
                    :label="item.title"
                    :value="item.id"
                    :disabled="item.status !== '1'"
                  />
                </el-select>
              </ul>
            </el-form-item>

            <el-divider />

            <el-form-item label="数据共享对象" required>
              <ul class="dataShare-edit">
                <li>
                  <el-select slot="prepend" v-model="select" placeholder="请选择" :disabled="isDetail">
                    <el-option label="用户" value="1" />
                    <el-option label="用户组" value="2" />
                  </el-select>
                </li>
                <li>
                  <!-- :disabled="item.status !== '1'" -->
                  <el-select
                    v-if="select === '1'"
                    v-model="ruleForm.uid"
                    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.nickname"
                      :value="item.id"
                    >
                      <span style="float: left">{{ item.nickname }}</span>
                      <span
                        style="
                          float: right;
                          color: #8492a6;
                          font-size: 13px;
                          padding: 0 25px 0 0;
                        "
                      >{{ item.role_name }}</span>
                    </el-option>
                  </el-select>
                  <el-select
                    v-else
                    v-model="ruleForm.data_group_id"
                    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.title"
                      :value="item.id"
                      :disabled="item.status !== '1'"
                    />
                  </el-select>
                </li>
              </ul>
            </el-form-item>

            <el-form-item label="共享的数据权限" prop="type">
              <el-radio v-model="ruleForm.type" label="1">读写</el-radio>
              <el-radio v-model="ruleForm.type" label="2">只读</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'
import resToken from '@/mixins/resToken'
import { shareRules } from './static'

export default {
  name: 'DataShare',
  mixins: [resToken],
  props: ['showModel', 'id', 'isDetail'],
  data() {
    return {
      loading: false,
      title: '添加共享规则',
      showModelThis: this.showModel,
      select: '1',
      sourceType: '1',
      activeOptions: [],
      actionList: [],
      ruleForm: {
        menu_ids: [],
        source_uid: '',
        source_data_group_id: '',
        uid: '',
        data_group_id: '',
        type: '1'
      },
      rulesThis: this.rules,
      rules: {
        menu_ids: [
          { required: true, message: '请选择共享的菜单', trigger: 'change' }
        ],
        source_uid: [
          { required: true, message: '请选择数据源用户', trigger: 'change' }
        ],
        source_data_group_id: [
          { required: true, message: '请选择数据源用户组', trigger: 'change' }
        ],
        uid: [
          { required: false, message: '请选择数据共享用户', trigger: 'change' }
        ],
        data_group_id: [
          { required: false, message: '请选择数据共享用户组', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择数据权限', trigger: 'change' }
        ]
      },
      dataForm: {
        name: '', // 业务员名字
        status: '' //
      },
      groupallList: [],
      dataUserGroups: [],
      shareUserGroups: []
    }
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.initForm()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
      }
    }
  },
  methods: {
    handleCloseModal() {
      this.ruleForm = {
        menu_ids: [],
        source_uid: '',
        source_data_group_id: '',
        uid: '',
        data_group_id: '',
        type: '1'
      }
      this.showModelThis = false
    },
    async initForm() {
      this.loading = true
      await this.initActionList()
      await this.getAllActive()
      await this.groupAllActive()
      if (this.id === 'add') {
        this.title = '添加共享规则'
        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

      this.$nextTick(() => this.$refs.ruleForm && this.$refs.ruleForm.clearValidate())
    },
    async initData() {
      const result = await asyncRequest.detail({ id: this.id })
      if (!result && result.code !== 0) return

      let { source_uid, source_data_group_id, data_group_id, uid } = result.data
      const { menu_ids, type } = result.data

      const convert = (str) => str === '0' ? '' : str

      source_data_group_id = convert(source_data_group_id)
      data_group_id = convert(data_group_id)
      source_uid = convert(source_uid)
      uid = convert(uid)

      this.select = data_group_id ? '2' : '1'
      this.sourceType = source_data_group_id ? '2' : '1'

      this.ruleForm = {
        menu_ids: menu_ids.split(','),
        source_data_group_id: source_data_group_id ? [source_data_group_id] : source_data_group_id,
        source_uid: source_uid ? [source_uid] : '',
        data_group_id: data_group_id ? [data_group_id] : '',
        uid: uid ? [uid] : '',
        type
      }
    },
    async initActionList() {
      const res = await asyncRequest.actionList({})
      if (res && res.code === 0) {
        const list = res.data
        const arr = list.filter((item) => item.child && item.child.length > 0)
        this.actionList = arr
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout()
      } else {
        this.$message.warning(res.message)
      }
    },
    async getAllActive() {
      const res = await asyncRequest.accountall(this.dataForm)
      if (res && res.code === 0 && res.data) {
        this.activeOptions = res.data
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout()
      } else {
        this.$message.warning(res.message)
      }
    },
    async groupAllActive() {
      const res = await asyncRequest.groupall(this.dataForm)
      if (res && res.code === 0 && res.data) {
        this.groupallList = res.data
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout()
      } else {
        this.$message.warning(res.message)
      }
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.clearValidate()
          this.ruleForm = {
            menu_ids: [],
            source_uid: '',
            source_data_group_id: '',
            uid: '',
            data_group_id: '',
            type: '1'
          }
        }
      })
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async(valid) => {
        if (!valid || this.loading) return
        const { data, source } = shareRules
        const isDataGroup = this.select === '2'
        const isSourceGroup = this.sourceType === '2'
        const method = this.id === 'add' ? 'add' : 'update'

        const { prop: dataProp, label: datalabel } = data[isDataGroup ? 'group' : 'user']
        const { prop: sourceProp, label: sourcelabel } = source[isSourceGroup ? 'group' : 'user']
        const soruceValue = this.ruleForm[sourceProp][0]
        const dataValue = this.ruleForm[dataProp][0]

        if (!soruceValue) return this.$message.warning(`请选择${sourcelabel}`)
        if (!dataValue) return this.$message.warning(`请选择${datalabel}`)

        if (isDataGroup && isSourceGroup) {
          if (soruceValue === dataValue) return this.$message.warning(`数据源共享用户组和数据共享用户组不能一致`)
        }

        if (!isDataGroup && !isSourceGroup) {
          if (soruceValue === dataValue) return this.$message.warning(`数据源共享用户和数据共享用户不能一致`)
        }

        const { menu_ids, source_uid, source_data_group_id, uid, data_group_id, type } = this.ruleForm

        const params = {
          uid: '',
          source_uid: '',
          data_group_id: '',
          source_data_group_id: '',
          ...(isSourceGroup ? { source_data_group_id: Number(source_data_group_id[0]) } : { source_uid: Number(source_uid[0]) }),
          ...(isDataGroup ? { data_group_id: Number(data_group_id[0]) } : { uid: Number(uid[0]) }),
          ...(method === 'update' ? { id: Number(this.id) } : {}),
          menu_ids,
          type
        }

        const result = await asyncRequest[method](params)

        if (result && result.code === 0) {
          const title = this.id === 'add' ? '添加成功' : '修改成功'

          this.$notify.success({
            title,
            message: ''
          })

          this.showModelThis = false
          this.$emit('refresh')
        } else if (result && result.code >= 100 && result.code <= 104) {
          await this.logout()
        } else {
          this.$message.warning(result.message)
        }
      })
    }
  }
}
</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>
