<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="680px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    :title="isUpdate ? '修改用户' : '添加用户'"
    @update:visible="updateVisible"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="82px">
      <el-form-item label="用户账号:" prop="username">
        <el-input
          clearable
          :maxlength="20"
          v-model="form.username"
          placeholder="请输入用户账号"
        />
      </el-form-item>
      <el-form-item label="手机号:" prop="mobile">
        <el-input
          clearable
          :maxlength="11"
          v-model="form.mobile"
          placeholder="请输入手机号"
        />
      </el-form-item>
      <el-form-item label="工号:" prop="userCode">
        <el-input clearable v-model="form.userCode" placeholder="请输入工号" />
      </el-form-item>
      <el-form-item label="城市:">
        <regions-select
          v-model="form.citys"
          type="provinceCity"
          placeholder="请选择省市"
          class="ele-fluid"
        />
      </el-form-item>
      <el-form-item label="合作渠道:" prop="orgId">
        <el-select v-model="form.orgId" clearable>
          <el-option
            v-for="(item, index) in orgList"
            :value="item.id"
            :key="index"
            :label="item.title"
          />
        </el-select>
      </el-form-item>
      <template v-if="form.orgId === 1">
        <el-form-item label="用户角色:" prop="roleIds">
          <el-select v-model="form.groupType" clearable>
            <el-option
              v-for="(item, index) in groupList"
              :value="index"
              :key="index"
              :label="item"
            />
          </el-select>
        </el-form-item>
      </template>
      <el-form-item label="备注:" prop="remark">
        <el-input
          type="textarea"
          clearable
          v-model="form.remark"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import { phoneReg } from 'ele-admin';
  import { addUser, groupTypeUsers, updateUser } from '@/api/organization/user';
  import { listOrganizations } from '@/api/organization/manage';
  import RegionsSelect from '@/components/RegionsSelect/index.vue';

  export default {
    components: { RegionsSelect },
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object
    },
    data() {
      const defaultForm = {
        id: null,
        username: '',
        mobile: '',
        userCode: '',
        groupType: '',
        orgId: '',
        citys: [],
        remark: ''
      };
      return {
        defaultForm,
        // 表单数据
        form: { ...defaultForm },
        // 表单验证规则
        rules: {
          username: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入用户名'
            }
          ],
          mobile: [
            {
              pattern: phoneReg,
              message: '手机号格式不正确',
              trigger: 'blur'
            }
          ],
          userCode: [
            {
              required: true,
              message: '请输入工号',
              trigger: 'blur'
            }
          ]
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        groupList: [],
        orgList: []
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    created() {
      // this.getGroupTypeList();
    },
    methods: {
      initData() {
        this.loadOrg();
        this.getGroupTypeList();
      },
      loadOrg() {
        return new Promise((resolve, reject) => {
          listOrganizations({ pid: 0 })
            .then((data) => {
              this.orgList = data;
              if (!this.form.orgId) {
                this.form.orgId = data[0]?.id || '';
              }
              resolve();
            })
            .catch((e) => {
              this.$message.error(e.message);
              reject(e);
            });
        });
      },
      getGroupTypeList() {
        groupTypeUsers()
          .then((data) => {
            this.groupList = data;
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      },
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.loading = true;
          const data = {
            ...this.form
          };
          const saveOrUpdate = this.isUpdate ? updateUser : addUser;
          saveOrUpdate(data)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        });
      },
      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      }
    },
    watch: {
      visible(visible) {
        if (visible) {
          this.initData();
          if (this.data && this.data.id) {
            this.$util.assignObject(this.form, {
              ...this.data
            });
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
          }
        } else {
          this.$refs.form.clearValidate();
          this.form = { ...this.defaultForm };
        }
      }
    }
  };
</script>
