<template>
  <div class="project-apploval">
    <div class="ls-row">
      <div class="row-header title">
        <span class="icon iconfont icon-shenpi1"></span>
        <span>审批操作</span>
      </div>
    </div>
    <template v-if="showOther">
      <div class="ls-row"
           style="justify-content: space-between;"
           v-if="taskShow.isStar">
        <span class="fb">项目星级</span>
        <span>
          <van-rate v-model="processForm.star"
                    :size="20"
                    icon="star-on"
                    void-icon="star-off"
                    :disabled="taskShow.flagStar" />
        </span>
      </div>
      <div class="ls-row"
           style="justify-content: space-between;"
           v-if="taskShow.isRepeat">
        <span class="fb">复评星级</span>
        <span>
          <van-rate v-model="processForm.repeatStar"
                    :size="20"
                    icon="star-on"
                    void-icon="star-off" />
        </span>
      </div>
      <div class="row-wrap p20 bb"
           v-if="taskShow.isPm">
        <div>
          <label>协助人员</label>
        </div>
        <aws-org ref="awsOrgRef"
                 :init-users-select="assistUsers"
                 :only-one="false"
                 @orgClose="setAssistUsers"></aws-org>
        <!-- <aws-org ref="awsOrgRef" v-model="assistUsers" :sid="sid"></aws-org>-->
      </div>

      <template v-if="taskShow.isVp">
        <div v-for="(item, index) in membersList"
             :key="index">
          <div class="row-wrap p20 bb">
            <div>
              <label>分配项目人员</label>
            </div>
            <van-button v-if="!index"
                        @click="addRow()"
                        type="info"
                        icon="plus"
                        size="small"></van-button>
            <van-button v-else
                        @click="deleteRow(index)"
                        type="info"
                        icon="minus"
                        size="small"></van-button>
            <aws-org ref="roleAwsOrgRef"
                     :init-users-select="item.users"
                     :only-one="false"
                     :indexNumber="index"
                     @orgClose="orgClose"></aws-org>
          </div>
          <van-field readonly
                     clickable
                     required
                     v-model="item.role"
                     label-width="50px"
                     label="角色"
                     placeholder="点击选择"
                     @click="addRole(index)" />
          <van-popup v-model="showRolePicker"
                     position="bottom">
            <van-picker show-toolbar
                        value-key="key"
                        :columns="memberRoleList"
                        @confirm="onRoleConfirm"
                        @cancel="showRolePicker = false" />
          </van-popup>
          <van-field readonly
                     clickable
                     required
                     v-model="item.productLine"
                     label-width="50px"
                     label="产品线"
                     placeholder="点击选择"
                     @click="addProductLine(index)" />
          <van-popup v-model="showProdLinePicker"
                     position="bottom">
            <van-picker show-toolbar
                        value-key="productLineName"
                        :columns="productLineList"
                        @confirm="onProdLineConfirm"
                        @cancel="showProdLinePicker = false" />
          </van-popup>
        </div>

      </template>
    </template>

    <div class="radio-wrap">
      <van-radio-group v-model="result"
                       @change="setResult">
        <van-radio icon-size="25px"
                   name="通过"
                   v-if="!taskShow.isButtion">同意</van-radio>
        <van-radio icon-size="25px"
                   name="驳回"
                   v-if="!taskShow.isButtion">驳回</van-radio>
        <van-radio icon-size="25px"
                   name="确认"
                   v-if="taskShow.isButtion">确认</van-radio>
      </van-radio-group>
    </div>
    <div class="text-content">
      <van-field v-model="msg"
                 rows="5"
                 autosize
                 class="textarea"
                 type="textarea"
                 maxlength="300"
                 placeholder="请输入备注说明"
                 show-word-limit />
    </div>

    <!-- <div class="footer-btn">
        <van-button  type="info">提交</van-button>
      </div> -->

  </div>
</template>

<script>
import commonSelect from '@/common/commonSelectList.js'
export default {
  name: 'project-apploval',
  created () {
    if (this.processId) {
      this.lineId = this.$common.getUrlParams('lineId')
      this.setTaskShow();
      this.getCollect();
    }

    this.sid = this.$common.getUrlParams('sid')

    this.getDataList()
  },
  methods: {
    addProductLine(index){
      this.index=index;
      this.showProdLinePicker=true;
    },
    addRole(index){
        this.index=index;
        this.showRolePicker = true;
    },
    orgClose (users, index) {
      this.membersList[index].users = users
    },
    // 负责人
    setAssistUsers (users) {
      this.assistUsers = users
    },
    setStar (star) {
      this.processForm.star = star || 0.5
    },
    valid (param) {
      var th = this
      if (param.actionName == null || param.actionName == '') {
        this.$toast({ type: 'fail', message: '请选择处理动作' })
        return false
      }
      if (param.actionName != null && param.actionName === '驳回' && !this.msg) {
        this.$toast({ type: 'fail', message: '请填写处理意见' })
        return false
      }
      if (this.taskShow.isStar && param.actionName !== '驳回') {
        if (this.processForm.star <= 1) {
          this.$toast({ type: 'fail', message: '初评项目星级必填' })
          return false
        }
      }
      if (this.taskShow.isRepeat && param.actionName !== '驳回') {
        if (this.processForm.repeatStar <= 1) {
          this.$toast({ type: 'fail', message: '复评项目星级必填' })
          return false
        }
      }
      if (this.taskShow.isPm && param.actionName !== '驳回') {
        if (this.assistUsers) {
          this.processForm.assistUsers = JSON.stringify(this.assistUsers)
        }
      }
      if (this.taskShow.isVp && param.actionName !== '驳回') {
        return this.membersList.every((item, index) => {
          if (!item.role || !item.users.length) {
            this.$toast({ type: 'fail', message: '分配项目人员的第' + (index + 1) + '行，数据未填写完整' })
            return false
          } else {
            let member = {
              role: item.role, // 角色
              productLines: item.productLine
            }
            item.users.forEach(function (user, i) {
              member.memberId = user.uid
              member.email = user.email
              member.name = user.name
              member.contactNumber = user.mobile
              member.job = user.role
              th.processForm.membersList.push(member)
            })

            return true
          }
        })
      } else {
        this.processForm.membersList = []
      }
      return true
    },
    setTaskShow () {
      // 项目申请，销售主管
      if (this.taskRefId == 'obj_c98557c805500001c6321e10619eaab0') {
        this.taskShow.isPm = true
        if (this.lineId && this.processForm.star >= 1) {
          this.taskShow.isStar = false
        } else {
          this.taskShow.isStar = true
          this.taskShow.isRepeat = false
          this.taskShow.flagStar = false
          this.taskShow.flagRepeat = true
        }
        // this.processForm.star=this.star;
      } else if (this.taskRefId == 'obj_c985b8e0bd0000016c3260901620198a') {
        if (this.lineId && this.processForm.star >= 1) {
          this.taskShow.isRepeat = false
        } else {
          this.taskShow.isStar = true
          this.taskShow.isRepeat = true
          this.taskShow.flagStar = true
          this.taskShow.flagRepeat = false
        }
      }else if(this.taskDefId=='obj_c985b8e39eb000011e131b006a506e30'){
        if(this.lineId && this.processForm.star>1){
          this.taskShow.isStar=false;
        }else{
          this.taskShow.isStar=true;
          this.taskShow.flagStar=false;
        }
      } else if (this.taskRefId == 'obj_c985b8e207200001f3448eb29a2019b0' ||
        this.taskRefId == 'obj_c985b8e376b00001dd2814f0169012bf' ||
        this.taskRefId == 'obj_c985b90742400001ab7618206ff08250') {
        this.taskShow.isVp = true
        if (this.taskRefId == 'obj_c985b8e207200001f3448eb29a2019b0' || this.taskRefId == 'obj_c985b90742400001ab7618206ff08250') {
          this.taskShow.isButtion = true
        }
      }
    },
    setParentValue (id, value) {
      try {
        if (parent) {
          parent.$('#' + id).val(value)
        }
      } catch (err) { }
    },
    setResult (val) {
      parent.setComment(val)
      // this.setParentValue('commentOption', val)
    },
    //获取审批时，收藏的数据
    getCollect(){
      this.$axios.post({
        domain: 'crmUrl',
        url: 'collect.findCollect',
        data: {
          moduleId: '3105',
          ext1: this.taskShow.isPm?'assistUsers':'members',
        },
        requestType: 'body',
        isShow: true,
        success: function (res) {
          if (res.errorCode === 200) {
             let data = res.data;
             if(data.length){
                let collectList = JSON.parse(data[0].collectData);
                 if(data[0].ext1 === 'assistUsers'){
                   collectList.forEach(item=>{
                      this.assistUsers.push(item);
                   })
                 } else if(data[0].ext1 === 'members'){
                   let _this =this;
                   this.membersList = [];
                   let newObj = {};
                   collectList.forEach((item, i)=>{
                     let newAry = [];
                     if(item.role && item.productLines){
                       if(!newObj[item.role] && !newObj[item.productLines]){
                         newAry.push({
                           name: item.name,
                           uid: item.memberId
                         })
                         _this.membersList.push({users: newAry, role: item.role, productLine: ''});
                         newObj[item.role] = item.role;
                         newObj[item.productLines] = item.productLines;
                       }
                     } else if(item.role){
                       if(!newObj[item.role]){
                         newAry.push({
                           name: item.name,
                           uid: item.memberId
                         })
                         _this.membersList.push({users: newAry, role: item.role, productLine: ''});
                         newObj[item.role] = item.role;
                       } else { //角色相同
                          _this.membersList.forEach( el =>{
                            if(el.role === item.role){
                             let valid =  el.users.every( e => e.uid !== item.memberId);
                             if(valid){
                               el.users.push({name: item.name, uid: item.memberId});
                             }
                            }
                          })
                       }
                     }

                   })

                   this.membersList.forEach((item, index) =>{
                     item.role = '';
                     _this.$refs.roleAwsOrgRef[index].defaultUsersSelectInfo = item.users;
                   })
                 }
             }
          }
        }.bind(this),
        error: function (res) {

        }.bind(this)
      })
    },
    onRoleConfirm (val) {
      this.membersList[this.index].role = val.vaule
      this.showRolePicker = false
    },
    onProdLineConfirm (val) {
      this.membersList[this.index].productLine = val.productLineName
      this.showProdLinePicker = false
    },
    addRow () {
      this.membersList.push({ role: '', productLine: '', users: [] })
    },
    deleteRow (index) {
      this.membersList.splice(index, 1)
    },
    async getDataList () {
      this.memberRoleList = await commonSelect.initDictDataPost(this, 'Crm_Member_Role')
      this.productLineList = await commonSelect.initProductLinePost(this)
    }
  },
  watch: {
    msg: {
      handler: function (val, oldval) {
        if (val) {
          this.setParentValue('msg', val)
        }
      }
    }
  },
  props: {
    showOther: {
      type: Boolean,
      default: false
    },
    taskRefId: {
      type: String,
      default: '',
      required: false
    },
    processId: {
      type: String,
      default: '',
      required: false
    }
  },
  data () {
    return {
      index:0,
      sid: '',
      star: 0,
      msg: '',
      result: '',
      showRolePicker: false,
      showProdLinePicker: false,
      memberRoleList: [],
      productLineList: [],
      taskShow: {
        isButtion: false,
        isPm: false,
        isVp: false,
        isStar: false,
        flagStar: true,
        isRepeat: false,
        flagRepeat: true
      },
      assistUsers: [],
      membersList: [{
        role: '', // 角色
        users: [],
        productLine: ''
      }],
      processForm: {
        assistUsers: '', // 协助人员，JSON格式
        // 项目成员,CPM、FAE
        membersList: [],
        moduleId: 3101, // 所属模块
        star: 0,
        repeatStar: 0
      }
    }
  }
}
</script>

<style type="text/css" scoped lang="scss">
.project-apploval {
  background-color: #fff;
  margin: 20px 0px;
  padding-bottom: 82px;

  .radio-wrap {
    padding: 25px 20px 10px;

    .van-radio-group {
      display: flex;
    }
    .van-radio {
      overflow: visible;
      margin-right: 25px;
    }
  }

  .textarea {
    border: none;
  }
  .row-wrap {
    position: relative;
    .van-button {
      position: absolute;
      right: 10px;
      top: 25px;
      z-index: 999;
      font-size: 14px;
    }
  }
}
</style>
