<template>
  <!-- 新增/编辑产品 -->
  <div class="addEditProduct">
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose" width="600px" :append-to-body="true" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="所属产品类别" prop="categoryId">
          <el-select
            v-model="form.categoryId"
            :disabled="!form.id"
            filterable
            remote
            reserve-keyword
            placeholder="请选择产品类别"
            v-SelectLazyLoading="lazyLoading"
            :remote-method="remoteMethod"
            :loading="loading"
            style="width:100%">
            <el-option
              v-for="item in productCategoryList.data"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名称"></el-input>
        </el-form-item>
        <el-form-item label="上市时间" prop="marketTime">
          <el-date-picker
            v-model="form.marketTime"
            type="date"
            placeholder="请选择上市时间"
            value-format="yyyy-MM-dd"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属公司" prop="companyName">
          <el-input v-model="form.companyName" :disabled="form.tenantId?true:false" placeholder="请输入所属公司"></el-input>
        </el-form-item>
        <el-form-item label="参考许可费率" prop="licenseRate">
          <el-input v-model="form.licenseRate" placeholder="请输入参考许可费率(介于 0 ~ 1 之间)"></el-input>
        </el-form-item>
        <el-form-item label="管理人" prop="rate">
          <div class="manage">
            <el-button size="small" @click="showDialog(2)">选择</el-button>
            <div v-html="getNames(form.adminPersons)">

            </div>
          </div>
        </el-form-item>
        <el-form-item label="谁可以看" prop="rate">
            <div  v-for="item in $constants.showType" :key="item.value" >
              <div>
                <el-radio :checked="item.value == form.showType" :label="item.value" :value="form.showType" @input="changeShowType(item.value)">{{item.label}}</el-radio>
              </div>
              <div v-if="form.showType && item.value == form.showType && [0,1].indexOf(item.value)==-1" class="person" @click="showDialog(1)">
                <p>选择朋友</p>
                <p v-html="getNames(form.persons)">
                </p>
              </div>
            </div>
        </el-form-item>
        <el-form-item label="图片" prop="">
          <el-upload ref="upload"  action="#" :auto-upload="false"  :on-change="handleChange"  list-type="picture" :show-file-list="false">
            <span v-if="form.systemFileList&&form.systemFileList.length>0" class="avatar">
              <span class="deleteImg">
                <span> 
                  <i class="el-icon-zoom-in" @click.stop="handlePictureCardPreview"></i>
                  <i class="el-icon-delete" @click.stop="handleRemove"></i>
                </span>
              </span>
              <el-image ref="image" style="width:100%;height: 100%;" :src="form.systemFileList[0].guid?$commonJS.checkViewer(form.systemFileList[0].guid):form.systemFileList[0].url" :preview-src-list="form.systemFileList?form.systemFileList.map(item=>{return item.guid? $commonJS.checkViewer(item.guid):item.url}):[]"></el-image>
            </span>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="产品说明" prop="productExplain">
          <el-input v-model="form.productExplain" type="textarea" :rows="2" placeholder="请输入产品说明"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="btnLoading" @click="submit">确定</el-button>
      </div>
    </el-dialog>
    <choose-person ref="choosePerson" @getPersonIds="getPersonIds"></choose-person>
  </div>
</template>

<script>
import choosePerson from '@/views/components/dialog/person.vue'
import { mapGetters } from 'vuex';
export default {
  components:{
    choosePerson
  },
  data() {
    const licenseRateRule = (rule , value ,callback)=>{
      if(value){
         if (!isNaN(value)) {
          if (value>=0 && value<=1) {
            callback()
          } else {
            callback(new Error('输入错误，参考许可费率介于0-1之间'))
          }
        } else {
          callback(new Error('输入错误，参考许可费率介于0-1之间'))
        }
      }else{
        callback()
      }
    }
    return {
      // 产品弹窗的title
      title: "",
      // 控制产品的关闭显示
      dialogVisible: false,
      // 产品表单的数据
      form: {},
      // 产品表单的校验
      rules: {
        categoryId: [{ required: true, message: '请输入所属产品类别', trigger: 'blur' },],
        name: [{ required: true, message: '请输入产品名称', trigger: 'blur' },],
        licenseRate:[{ required: false, validator:licenseRateRule, trigger: 'blur' },],
      },
      //产品类别集合
      productCategoryList:{
        data:[],
        queryParams:{//产品类别分页信息
          size:10,
          current:1
        },
      },
      loading:false,
      //待上传的文件
      file:[],
      //选择类型是管理人还是谁都可以看
      chooseType:1,
      //按钮加载
      btnLoading:false,
    };
  },
  computed:{
    ...mapGetters(['userinfo'])
  },
  mounted() { 
    
  },
  methods: {
    // 上传的change
    handleChange(file,fileList){
      this.$set(this.form,'systemFileList', [{url:file.url}])
      this.file = [file.raw]
    },
    // 点击已上传的文件
    handlePictureCardPreview(file) {
      this.$refs.image.showViewer = true
     },
    // 文件列表移除文件
    handleRemove(file) {
      this.file = []
      this.form.systemFileList = []//直接清空适用于单张图片
     },
    // 打开弹窗
    async open(row) {
      this.form = JSON.parse(JSON.stringify(row))
      if(!this.form.showType && this.form.showType!=0){
        this.$set(this.form,'showType',0)
      }
      if (this.form.id) {
        this.title = '编辑产品'
      } else {
        if (this.form.isTheCompany=='1') {
          // 获取所属租户公司
          this.form.companyName = this.userinfo.tenantName
          this.form.tenantId = this.userinfo.tenantId
          this.title = '新增本公司产品'
        } else {
          this.title = '新增外公司产品'
        }
      }
      this.productCategoryList.data=[]
      this.productCategoryList.queryParams.current = 1
      if(this.form.categoryId){
        var params ={
          ...this.productCategoryList.queryParams,
          searchQuery:`category_id=${this.form.categoryId}`
        }
       await this.getProductCategory(params,1)
      }
      if(!this.form.id){
        this.getProductCategory(this.productCategoryList.queryParams);
      }
      
      this.dialogVisible = true;
    },
    // 弹窗确定
    submit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          var formData = new FormData()
          this.form.guids = (this.form.systemFileList||[]).map(item=>{
            return item.guid
          })
          formData.append('product',JSON.stringify(this.form))
          if(this.file.length>0){
            this.file.forEach(item=>{
              formData.append("files", item);
            })
          }
          this.btnLoading = true
          if(this.form.id){
            this.$api.updateProduct(formData).then(response=>{
              this.$message.success('更新成功')
              this.$emit('getMessage','更新成功')
              this.btnLoading = false
              this.handleClose()
            }).catch(error=>{
              this.btnLoading = false
            })
          }else{
            this.$api.addProduct(formData).then(response=>{
              this.$message.success('添加成功')
              this.$emit('getMessage',this.form.categoryId)
              this.btnLoading = false
              this.handleClose()
            }).catch(error=>{
              this.btnLoading = false
            })
          }
          
        } else {
          
        }
      })
    },
    // 弹窗取消/关闭
    handleClose() {
      this.$refs.ruleForm.resetFields()
      this.dialogVisible = false;
    },
    // 下拉框懒加载
    lazyLoading() {
      if(this.productCategoryList.queryParams.current * this.productCategoryList.queryParams.size >= this.productCategoryList.queryParams.total){
        return false
      }
      this.productCategoryList.queryParams.current++;
      var params ={
          ...this.productCategoryList.queryParams,
          searchQuery:`category_name=${this.productCategoryList.name}`
        }
      this.getProductCategory(params);
    },
    //远程搜索产品类别
    remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          this.productCategoryList.name=query
          var params = {
            ...this.productCategoryList.queryParams,
            searchQuery:`category_name=${query}`
          }
          this.$api.queryProductCategory(params).then(response=>{
            if(response.code == 200){
              this.loading = false;
              this.productCategoryList.data = response.data.data
            }
          }).catch(error=>{
            this.loading = false;
          })
        } else {
          this.productCategoryList.name = null
          this.productCategoryList.data = [];
          this.getProductCategory(this.productCategoryList.queryParams)
        }
    },
    //获取产品类别列表
    async getProductCategory(params,type){
     await this.$api.queryProductCategory(params).then(response=>{
        if(response.code == 200){
          if(!type){
            if(this.form.categoryId){
              var index = response.data.data.findIndex(item=>{
                return item.id == this.form.categoryId
              })
              if(index!=-1){
                response.data.data.splice(index,1)
              }
            }
            this.productCategoryList.queryParams.total = response.data.total
          }
          
          this.productCategoryList.data.push(...response.data.data);
        }
      }).catch(error=>{
      })
    },
     //切换谁可以看类型
     changeShowType(val){
      this.form.showType1 = this.form.showType
      this.$set(this.form,'showType',val)
      this.$set(this.form,'persons',[])
      this.$set(this.form,'showPersonIds',[])
      if(this.form.showType == 2 || this.form.showType == 3){
        this.showDialog(1)
      }
      
    },
    //打开人员弹窗
    showDialog(type){
      this.chooseType = type
      if(type == 2){
        this.$refs.choosePerson.open(this.form.adminIds,this.form.adminPersons)
        return false
      }
      this.$refs.choosePerson.open(this.form.showPersonIds,this.form.persons)
    },
    //获取人员信息
    getPersonIds({personIds,persons}){
      if(this.chooseType == 2){
        if(personIds.length>0){
          this.$set(this.form,'adminPersons',persons)
          this.$set(this.form,'adminIds',personIds)
        }else{
          this.$set(this.form,'adminPersons',[])
          this.$set(this.form,'adminIds',[])
        }
        return false
      }
      if(personIds.length>0){
        this.$set(this.form,'persons',persons)
        this.$set(this.form,'showPersonIds',personIds)
      }else{
        if(this.form.showType == this.form.showType1){
          this.$set(this.form,'showType',0)
        }else{
          this.$set(this.form,'showType',this.form.showType1)
        }
        
        this.$set(this.form,'persons',[])
        this.$set(this.form,'showPersonIds',[])
      }
    },

    getNames(row){
      if(!row){
        return ''
      }
      var arr = row.map(item=>{
        return item.name
      })
      return arr.join('、')
    }
  },
};
</script>
<style lang="scss">
.el-table__row{
  border: 1px solid black !important;
}
</style>
<style lang="scss" scoped>
.manage{
  display: flex;
  align-items: center;
  height: 40px;
  div{
    width:100%;
    padding-left:10px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow:ellipsis;
  }
}
.person{
  height:50px;
  padding-left:30px;
  cursor: pointer;
  p{
    margin:0;
    height: 30px;
    line-height: 30px;
  }
  p:first-child{
    color: green;
  }
  p:last-child{
    font-size: 12px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow:ellipsis;
  }
}

.avatar-uploader-icon {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.avatar {
  position: relative;
  width: 148px;
  height: 148px;
  display: block;
  .deleteImg {
    display: none;
    font-size: 30px;
    width: 148px;
    height: 148px;
    background-color: black;
    opacity: 0.6;
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    margin: auto;
    z-index: 999;
  }
  
  .deleteImg span i {
    margin-left: 10px;
    color: #fff;
  }
  
  .deleteImg span {
    display: flex;
    align-items: center;
    /*垂直居中*/
    justify-content: center;
    /*水平居中*/
    width: 100%;
    height: 100%;
  }
}

.avatar:hover .deleteImg {
  display: block;
}

</style>
