<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="10vh"
    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 style="margin-top: -20px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :rules="rulesThis"
            label-width="80px"
            class="demo-ruleForm"
          >
            <el-form-item label="组名称" prop="title">
              <el-input
                v-model="ruleForm.title"
                placeholder="请输入组名称"
                maxlength="50"
                :disabled="isDetail"
              />
            </el-form-item>
            <!-- :disabled="item.status !== '1'" -->
            <el-form-item label="组成员" prop="uids">
              <el-select
                v-model="ruleForm.uids"
                multiple
                filterable
                clearable
                :disabled="isDetail"
                class="setWidth"
              >
                <el-option
                  v-for="item in activeOptions"
                  :key="`group_user` + 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-form-item>

            <el-form-item label="共享类型" prop="type">
              <el-select
                v-model="ruleForm.type"
                style="width:100%"
                placeholder="请选择共享类型"
                :disabled="isDetail"
              >
                <el-option
                  v-for="shareType in shareTypes"
                  :key="shareType.value"
                  v-bind="shareType"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="ruleForm.remark"
                type="textarea"
                placeholder="请输入备注"
                :rows="5"
                maxlength="300"
                show-word-limit
                :disabled="isDetail"
              />
            </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/group'
import resToken from '@/mixins/resToken'
import { shareTypes } from './static'
export default {
  name: 'Group',
  mixins: [resToken],
  props: ['showModel', 'id', 'isDetail'],
  data() {
    return {
      shareTypes,
      userList: [],
      loading: false,
      title: '添加用户组',
      showModelThis: this.showModel,
      ruleForm: {
        title: '',
        uids: [],
        type: '',
        remark: ''
      },
      rulesThis: this.rules,
      rules: {
        title: [
          {
            required: true,
            message: '请输入组名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 30,
            message: '长度在 2 到 30 个字符',
            trigger: 'blur'
          }
        ],
        uids: [
          {
            required: true,
            message: '请选择数据共享用户',
            trigger: 'change'
          }
        ],
        type: [
          {
            required: true,
            message: '请选择共享类型',
            trigger: 'change'
          }
        ],
        remark: [
          {
            required: true,
            message: '请输入备注',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 300,
            message: '长度在 2 到 300 个字符',
            trigger: 'blur'
          }
        ]
      },

      dataForm: {
        name: '', // 业务员名字
        status: '' //
      },
      activeOptions: []
    }
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.initForm()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
      }
    }
  },
  methods: {
    handleCloseModal() {
      this.showModelThis = false
      this.ruleForm = {
        title: '',
        uids: [],
        type: '',
        remark: ''
      }
    },
    async initForm() {
      this.loading = true
      await this.getAllActive()
      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 res = await asyncRequest.detail({ id: this.id })
      if (res && res.code === 0) {
        const { remark, title, type, user_list } = res.data
        this.ruleForm = {
          title,
          type,
          remark,
          uids: user_list.map(u => u.uid)
        }
        this.userList = user_list
      } 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 = {
            title: '',
            uids: [],
            type: '',
            remark: ''
          }
        }
      })
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async valid => {
        if (!valid || this.loading) return

        const method = this.id === 'add' ? 'add' : 'update'
        let param = { ...this.ruleForm }

        switch (method) {
          case 'update':
            // eslint-disable-next-line no-case-declarations
            const delUsers = this.userList
              .filter(({ uid }) => !this.ruleForm.uids.includes(uid)).map(({ uid, id }) => ({
                uid,
                id,
                is_del: 1
              }))

            // eslint-disable-next-line no-case-declarations
            const originUsers = this.userList
              .filter(({ uid }) => this.ruleForm.uids.includes(uid)).map(({ uid, id }) => ({
                uid,
                id,
                is_del: 0
              }))

            // eslint-disable-next-line no-case-declarations
            const addUsers = this.ruleForm.uids
              .filter(_uid => !originUsers.find(({ uid }) => uid === _uid) && !delUsers.find(({ uid }) => uid === _uid))
              .map(uid => ({
                uid: Number(uid),
                is_del: 0,
                id: null
              }))

            param = {
              ...param,
              id: this.id,
              uids: [...delUsers, ...originUsers, ...addUsers]
            }
            break

          case 'add':
            param = {
              ...param,
              id: this.id,
              uids: this.ruleForm.uids.map(uid => ({ uid }))
            }
            break
        }

        this.loading = true
        const result = await asyncRequest[method](param)
        this.loading = false

        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)
        }
      })
    },
    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)
      }
    }
  }
}
</script>

   <style lang="scss" scoped>
.group {
  .setWidth {
    width: 100% !important;
    // display: flex;
    // display: block !important;
    // .el-input__inner {
    //   display: flex;
    //   width: 1000px !important;
    //   display: block !important;
    // }
  }
}
</style>
