<!-- 团队编辑弹窗 -->
<template>
  <ele-modal
    width="680px"
    :visible="visible"
    :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-row :gutter="15">
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item label="上级团队:">
            <team-select
              v-model="form.parentId"
              :data="teamList"
              placeholder="请选择上级团队"
            />
          </el-form-item>
          <el-form-item label="团队名称:" prop="teamName">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.teamName"
              placeholder="请输入团队名称"
            />
          </el-form-item>
          <el-form-item label="所属机构:" v-show="form.parentId ? false : true">
            <team-org-select v-model="form.organizationId" />
          </el-form-item>
          <el-form-item label="所在城市:">
            <regions-select
              v-model="form.city"
              placeholder="请选择省市"
              type="provinceCity"
              class="ele-fluid"
            />
          </el-form-item>
          <el-form-item
            label="logo:"
            v-show="form.teamType == 1 ? true : false"
          >
            <ele-image-upload
              v-model="form.logo"
              :limit="1"
              :drag="true"
              :multiple="false"
              :upload-handler="logoHandler"
              @upload="onUpload"
            />
            <div class="ele-text-secondary">建议尺寸100X100</div>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item label="团队类型:" prop="teamType">
            <team-type-select v-model="form.teamType" />
          </el-form-item>
          <el-form-item label="团队id:" v-if="form.teamId">
            <el-input v-model="form.teamId" disabled />
          </el-form-item>
          <el-form-item label="排序号:">
            <el-input-number
              :min="0"
              :max="99999"
              v-model="form.sortNumber"
              controls-position="right"
              placeholder="请输入排序号"
              class="ele-fluid ele-text-left"
            />
          </el-form-item>
          <el-form-item label="备注:">
            <el-input
              :rows="4"
              type="textarea"
              :maxlength="200"
              v-model="form.comments"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </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 TeamSelect from './team-select.vue';
  import TeamTypeSelect from './team-type-select.vue';
  import TeamOrgSelect from './team-org-select.vue';
  import RegionsSelect from '@/components/RegionsSelect/index.vue';
  import EleImageUpload from 'ele-admin/es/ele-image-upload';
  import request from '@/utils/request';
  import { addTeam, updateTeam } from '@/api/institution/team';

  export default {
    components: {
      TeamSelect,
      TeamTypeSelect,
      TeamOrgSelect,
      RegionsSelect,
      EleImageUpload
    },
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object,
      // 上级id
      parentId: null,
      // 团队数据
      teamList: Array
    },
    data() {
      const defaultForm = {
        teamId: null,
        parentId: null,
        teamName: '',
        teamType: null,
        sortNumber: null,
        comments: '',
        city: [],
        logo: [],
        organizationId: null
      };
      return {
        defaultForm,
        // 表单数据
        form: { ...defaultForm },
        // 表单验证规则
        rules: {
          teamName: [
            {
              required: true,
              message: '请输入团队名称',
              trigger: 'blur'
            }
          ],
          bizIds: [
            {
              required: true,
              message: '请选择所属机构',
              trigger: 'blur'
            }
          ]
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    methods: {
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.loading = true;
          const data = {
            ...this.form,
            parentId: this.form.parentId || 0
          };
          const saveOrUpdate = this.isUpdate ? updateTeam : addTeam;
          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);
            });
        });
      },
      /* 上传事件 */
      logoHandler(file) {
        const item = {
          file,
          uid: file.uid,
          name: file.name,
          progress: 0,
          status: null
        };
        if (!file.type.startsWith('image')) {
          this.$message.error('只能选择图片');
          return;
        }
        if (file.size / 1024 / 1024 > 2) {
          this.$message.error('大小不能超过 2MB');
          return;
        }
        item.url = window.URL.createObjectURL(file);
        // 关键就是这里要自己 push 添加数据而不是靠 v-modal 自动更新
        this.form.logo.push(item);
        this.onUpload(item);
      },
      /* 上传 item */
      onUpload(item) {
        item.status = 'uploading';
        const formData = new FormData();
        formData.append('file', item.file);
        request({
          url: '/upload',
          method: 'post',
          data: formData,
          onUploadProgress: (e) => {
            if (e.lengthComputable) {
              item.progress = (e.loaded / e.total) * 100;
            }
          }
        })
          .then((res) => {
            if (res.data.code === 0) {
              item.status = 'done';
              item.url = res.data.data.full_url;
              item.fileUrl = res.data.data.url;
            }
          })
          .catch(() => {
            item.status = 'exception';
          });
      },
      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      }
    },
    watch: {
      visible(visible) {
        if (visible) {
          if (this.data) {
            this.$util.assignObject(this.form, this.data);
            this.isUpdate = true;
          } else {
            this.form.parentId = this.parentId;
            this.isUpdate = false;
          }
        } else {
          this.$refs.form.clearValidate();
          this.form = { ...this.defaultForm };
        }
      }
    }
  };
</script>
