<template>
  <el-dialog
    :visible.sync="isShow"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    @close="cancelHandle"
    custom-class="variety-set-dialog"
    top="10vh"
    v-dialogDrag
    :title="form.VarietyId?'编辑品种':'添加品种'"
		width="650px"
  >
    <div class="main">
      <el-form
        ref="form"
        class="form-cont"
        label-position="left"
        label-width="80px"
        :model="formData"
        :rules="formRules"
      >
        <el-form-item label="品种" prop="varietyName">
          <el-input
            v-model="formData.varietyName"
            style="width: 340px"
            placeholder="请输入品种"
          />
        </el-form-item>
        <el-form-item label="设置权限" prop="users">
          <el-cascader
            ref="cascader"
            v-model="formData.users"
            :options="researcherList"
            :show-all-levels="false"
            filterable
            :props="{
              children: 'ResearcherList',
              emitPath: false,
              multiple: true
            }"
            :key="cascaderIdx"
            clearable
            collapse-tags
            placeholder="请选择研究员"
            @remove-tag="removeResearchersChange"
            style="width:80%"
          />
        </el-form-item>
        <el-form-item label="已选用户">
          <ul class="choose-users">
            <li v-for="(item,index) in chooseUsers" :key="item">
              {{item}}
              <span v-if="index!==chooseUsers.length-1">、</span>
            </li>
          </ul>
        </el-form-item>
      </el-form>
    </div>
    <div class="dia-bot">
			<el-button type="primary" style="margin-right: 20px" @click="saveHandle">保存</el-button>
			<el-button type="primary" plain @click="cancelHandle('cancel')">取消</el-button>
		</div>
  </el-dialog>
</template>

<script>
import {roadshowInterence} from '@/api/modules/roadshowApi.js';
import * as supplyApi from '@/api/modules/supplyApi.js';
export default {
  props: {
    isShow: {
      type: Boolean
    },
    form: {
      type: Object
    }
  },

  watch: {
    isShow(nval) {
      if(!nval) return
      this.getResearcherList();
      if(this.form.VarietyId) {
        this.formData = {
          users: this.form.PermissionUserId.split(',').map(_ => Number(_)),
          varietyName: this.form.VarietyName
        }
      }
    },

    'formData.users': {
      handler(nval) {
        this.chooseUsers = this.researcherList.length && nval.map(_ => this.getUserName(_)).filter(_ => _);
      }
    }
  },
  data() {
    return {
      cascaderIdx:0,
      formData: {
        varietyName: '',
        users: [] 
      },
      researcherList: [],

      chooseUsers:[]
    }
  },

  methods: {
    cancelHandle() {
      this.formData = {
        varietyName: '',
        users: [] 
      };
      this.researcherList = [];
      this.chooseUsers = [];
      ++this.cascaderIdx;
      this.$emit('update:isShow',false)
    },

    /* 保存 */
    async saveHandle() {
      await this.$refs.form.validate();
      const { varietyName,users } = this.formData;
      console.log(this.formData)
      let params = {
        VarietyName: varietyName,
        AdminIdList: users
      }
      const res = this.form.VarietyId 
        ? await supplyApi.editVariety({VarietyId: this.form.VarietyId,...params})
        : await supplyApi.addVariety(params)

      if(res.Ret !== 200) return
      this.$message.success('保存成功')
      this.cancelHandle();
      this.$emit('successBack')
    },

    getUserName(id) {
      let name = '';
      this.researcherList.forEach(item => {
        item.ResearcherList && item.ResearcherList.forEach(item2 => {
            if(item2.AdminId === id) {
              name = item2.RealName || '';
            }
        })
      })
      return name
    },

    // 选择的研究员发生改变
    removeResearchersChange(val) {
      this.formData.users = this.formData.users.filter(item => item !== val)
      this.cascaderIdx++;
      
    },

    /* 获取研究员列表 */
    async getResearcherList() {
      const res = await roadshowInterence.getResearcherList();
      if (res.Ret !== 200) return
      
      this.researcherList = this.formatResearcherList(res.Data);

      if(this.form.VarietyId) this.chooseUsers = this.researcherList.length && this.formData.users.map(_ => this.getUserName(_)).filter(_ => _);
    },

    // 对获取到的研究员列表做处理
    formatResearcherList(list) {
      list.forEach((group) => {
        // 对组做处理
        group.label = group.GroupName;
        // 如果有列表
        if (group.ResearcherList) {
          group.ResearcherList.forEach((item) => {
            // 对研究员做处理
            item.label = item.RealName;
            item.value = item.AdminId;
          });
        } else {
          // 没有列表
          group.value = group.GroupId;
        }
      });
      return list;
    },
  }
}
</script>

<style lang="scss" scoped>
.main {
  padding: 0 50px;
}
.dia-bot {
  display: flex;
  justify-content: center;
  margin: 40px 0;
}
.choose-users {
  display: flex;
  flex-wrap: wrap;
}
</style>
<style lang="scss">
.variety-set-dialog {
  .el-cascader .el-input {width: 100% ;}
}
</style>