<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    v-if="visible"
    :visible.sync="visible"
    :title="title"
    :close-on-click-modal="false"
    width="60%"
    @close="cancel"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <headerTitle title="基本信息"></headerTitle>
      <el-row>
        <el-col :span="12">
          <el-form-item label="组名" prop="name" style="margin-bottom: 22px">
            <el-input
              v-model="form.name"
              placeholder="请选择输入组名"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="描述"
            prop="description"
            style="margin-bottom: 22px"
          >
            <el-input
              v-model="form.description"
              placeholder="请选择输入描述"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成员" style="margin-bottom: 22px">
            <!-- <el-input
              @click.native="handlAdd"
              v-model="form.memberUserIds"
              placeholder="请选择成员"
            ></el-input> -->
            <el-button type="primary" @click="handlAdd">选择成员</el-button>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="status" label="状态">
            <el-radio-group v-model="form.status">
              <el-radio :label="0">开启</el-radio>
              <el-radio :label="1">关闭</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="footer">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="cancel">返回</el-button>
    </div>

    <headerTitle title="成员列表" style="margin-top: 15px"></headerTitle>
    <ele-pro-table
      ref="table"
      :needPage="false"
      :columns="columns"
      :datasource="form.userList"
      cache-key="systemRoleTable21"
    >
      <!-- 操作列 -->
      <template v-slot:action="{ row }">
        <el-popconfirm
          class="ele-action"
          title="确定要删除此角色吗？"
          @confirm="remove(row)"
        >
          <template v-slot:reference>
            <el-link type="danger" :underline="false" icon="el-icon-delete">
              删除
            </el-link>
          </template>
        </el-popconfirm>
      </template>
    </ele-pro-table>
    <staffSelection
      type="bpm"
      ref="staffSelection"
      @confirm="confirmStaffSelection"
      :hasAccount="1"
    ></staffSelection>
  </ele-modal>
</template>
<script>
  import {
    createUserGroup,
    updateUserGroup,
    getUserGroup
  } from '@/api/bpm/userGroup';
  import staffSelection from '@/views/workforceManagement/team/components/staffSelection.vue';
  let formDef = {
    id: '',
    description: null,
    status: 0,
    name: '',
    memberUserIds: [],
    userList: []
  };
  export default {
    components: { staffSelection },
    data() {
      return {
        visible: false,
        title: '',
        columns: [
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'name',
            label: '姓名'
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 220,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ],
        form: { ...formDef },
        rules: {
          name: [
            { required: true, message: '请输入组名', trigger: 'change' }
          ],
          description: [
            { required: true, message: '请输入描述', trigger: 'change' }
          ]
        },

        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false
      };
    },
    created() {},

    methods: {
      //获取详情
      async getDetailData(id) {
        this.loading = true;
        let data = await getUserGroup(id);
        this.loading = false;
        if (data) {
          this.form = data;
        
          // this.$nextTick(() => {

          // });
        }
      },

      async open(type, row, contactCategoryId) {
        this.title = type === 'add' ? '新增用户组' : '修改用户组';
        this.row = row;
        this.visible = true;
        if (type == 'add') {
          this.isUpdate = false;
        } else {
          this.isUpdate = true;
          this.getDetailData(row.id);
        }
        // this.init(row.id);
      },

      getValidate() {
        return Promise.all([
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          })
        ]);
      },

      async save() {
        // return;

        try {
          await this.getValidate();
          // 表单验证通过，执行保存操作
          this.loading = true;
          if (this.form.userList.length == 0) {
            this.$message.warning('请选择成员');
            return;
          }
          if (!this.isUpdate) {
            delete this.form.id;
          }
          this.form.memberUserIds = this.form.userList.map((item) => item.id);
          if (this.isUpdate) {
            updateUserGroup(this.form)
              .then((res) => {
                this.loading = false;
                this.$message.success('修改成功');
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          } else {
            createUserGroup(this.form)
              .then((res) => {
                this.loading = false;
                this.$message.success('新增成功');
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          }
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      handlAdd() {
        this.$refs.staffSelection.open(
          JSON.parse(JSON.stringify(this.form.userList))
        );
      },
      remove(row) {
        let index = this.form.userList.findIndex((n) => n.id == row.id);
        if (index !== -1) {
          this.form.userList.splice(index, 1);
        }
      },
      confirmStaffSelection(data) {
        this.form.userList = data;
      },
      cancel() {
        this.$nextTick(() => {
          this.form = formDef;

          this.visible = false;
        });
      }
    }
  };
</script>
