<template>
  <div class="study-subject">
    <div class="subject-top">{{study.name}}</div>
    <div class="subject-study">
      <div class="study-info">{{$t('page.business.study.study.sn')}}：<span>{{study.sn}}</span></div>
      <div class="study-info">{{$t('page.business.study.study.name')}}：<span>{{study.name}}</span></div>
      <div class="study-info">{{$t('page.business.study.study.createDate')}}：<span>{{study.createTime}}</span></div>
    </div>
    <div class="subject-operate">
      <div class="operate-img"></div>
      <div class="operate-left">{{$t('page.business.study.studyEnter.syxkxx')}}</div>
      <div class="operate-right">
        <i class="el-icon-edit operate-icon" @click="editSubject" v-if="operate && (study.leader==userId || checkRole(['TFM']))"></i>
      </div>
    </div>
    <div class="subject-content">
      <div class="subject-item" :class="selectedSubjectId===item.id?'active':''" v-for="(item,index) in  subjectList" :key="index" @click="changeSelectedSubject(item)">
        <div class="subject-item-name">{{item.deptName}}({{$i18n.locale === 'zh_CN'?item.leaderName:item.leaderNameEn}})</div>
        <div class="subject-item-add" v-if="operate && item.leader==userId">
          <el-button type="primary" plain @click.stop="yq(item)">{{$t('page.business.study.studyEnter.yq')}}</el-button>
        </div>
      </div>
    </div>

    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :title="infoDialog.title" :visible.sync="infoDialog.visible" width="800px" append-to-body>
      <el-table v-loading="infoDialog.loading" :data="infoDialog.list">
        <el-table-column label="" type="index" width="50">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.select"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column :label="$t('page.business.study.studyEnter.xk')" prop="deptName" align="center" />
        <el-table-column :label="$t('page.business.study.studyEnter.czfzr')" align="center">
          <template slot-scope="scope">
            <div class="subject-table-box">
              <div class="subject-table-left">
                <el-input v-if="$i18n.locale === 'zh_CN'" v-model="scope.row.leaderName" maxlength="100" readonly />
                <el-input v-else v-model="scope.row.leaderNameEn" maxlength="100" readonly />
              </div>
              <div class="subject-table-right">
                <el-button type="primary" plain @click="chooseLeader(scope.row)">{{$t('page.business.study.studyEnter.xzfzr')}}</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save">{{$t('form.saveConfirm')}}</el-button>
        <el-button @click="infoDialog.visible = false">{{$t('form.cancel')}}</el-button>
      </div>
    </el-dialog>

    <SelectDeptUserDialog ref="selectSubjectDeptUserDialog" @change="changeSubject" />
    <SelectDeptUserMultipleDialog ref="selectSubjectDeptUserMultipleDialog" @change="changeMember" />

    <Sign ref="subjectSignRef" @callback="doSign" />
  </div>
</template>

<script>
import { checkPermi, checkRole } from "@/utils/permission";
import {
  studySubject_listByStudyId,
  studySubject_getAllListByStudyId,
  studySubject_save
} from '@/api/business/study/studySubject'
import {
  studySubjectUser_getListByStudySubjectId,
  studySubjectUser_save
} from '@/api/business/study/studySubjectUser'
import SelectDeptUserDialog from '@/views/business/comps/select/SelectDeptUserDialog.vue';
import SelectDeptUserMultipleDialog from '@/views/business/comps/select/SelectDeptUserMultipleDialog.vue';
import Sign from './sign.vue'
export default {
  name: 'StudySubject',
  props: {
    study:{
      type:Object,
      default:()=>{
        return {}
      },
      deep: true,
    },
    operate:{
      type:Boolean,
      default:false
    }
  },
  watch: {
    study: {
      immediate: true,
      handler(v) {
        this.getList()
      }
    },
  },
  components: {SelectDeptUserDialog,SelectDeptUserMultipleDialog,Sign},
  filters: {},
  data() {
    return {
      userId:this.$store.getters.id,
      subjectList:[],
      selectedSubjectId:'',
      infoDialog:{
        title:this.$t('page.business.study.studyEnter.xzxk'),
        visible:false,

        loading:false,
        list:[],
        subject:{
          leader:'',
          leaderName:'',
          leaderNameEn:'',
        },

        saveList:[]
      },

      memberSubject:{},

      signType:'',
      memberList:[]
    }
  },
  created() {},
  methods: {
    checkPermi,
    checkRole,
    getList(){
      if(this.study.id){
        this.selectedSubjectId = ''
        studySubject_listByStudyId({studyId:this.study.id}).then(response => {
          this.subjectList = response.data;
          for(let i=0;i<this.subjectList.length;i++){
            let item = this.subjectList[i]
            if(item.leader==this.userId || (item.userIdList && item.userIdList.length>0 && item.userIdList.indexOf(this.userId)>-1)){
              this.selectedSubjectId = item.id
              break
            }
          }
          if(this.selectedSubjectId === ''){
            this.selectedSubjectId = this.subjectList.length>0?this.subjectList[0].id:''
          }
          
          this.$emit('change',this.selectedSubjectId)
        })
      }
    },
    changeSelectedSubject(item){
      this.selectedSubjectId = item.id
      this.$emit('change',this.selectedSubjectId)
    },
    editSubject(){
      this.infoDialog.list = []
      this.infoDialog.loading = true
      studySubject_getAllListByStudyId({studyId:this.study.id}).then(response => {
        this.infoDialog.list = response.data;
        this.infoDialog.visible = true;
      }).finally(()=>{
        this.infoDialog.loading = false;
      });
    },
    save(){
      let postList = _.filter(this.infoDialog.list, (o)=> { return o.select })
      if(postList.length>0){
        for(let i=0;i<postList.length;i++){
          let item = postList[i]
          if(!item.leader || !item.leaderName){
            this.$message.error(`${item.deptName}还没设置负责人`)
            return false
          }
        }
      }
      this.infoDialog.saveList = postList
      this.signType = 'save'
      this.$refs.subjectSignRef.show(this.$t('page.business.study.study.rybg'),this.$t('page.business.study.study.rybg'))
    },
    doSign(val){
      if(this.signType==='save'){
        this.doSave(val)
      }
      if(this.signType==='member'){
        this.doChangeMember(val)
      }
    },
    doSave(sign){
      this.$modal.loading()
      studySubject_save({
        studyId:this.study.id,
        subjectList:this.infoDialog.saveList,
        sign:sign
      }).then(() => {
        this.infoDialog.visible = false
        this.$refs.subjectSignRef.cancel()
        this.getList()
      }).finally(() => {
        this.$modal.closeLoading()
      })
    },
    chooseLeader(row){
      this.infoDialog.subject = row
      this.$refs.selectSubjectDeptUserDialog.show(this.infoDialog.subject.leader,this.infoDialog.subject.leaderName,this.infoDialog.subject.leaderNameEn)
    },
    changeSubject(val){
      this.infoDialog.subject.leader = val.id
      this.infoDialog.subject.leaderName = val.name
      this.infoDialog.subject.leaderNameEn = val.nameEn
      this.infoDialog.subject.select = true
      let index = _.findIndex(this.infoDialog.list,(item)=>{
        return item.deptId===this.infoDialog.subject.deptId
      })
      if(index>-1){
        this.infoDialog.list.splice(index,1,this.infoDialog.subject)
      }
    },

    yq(item){
      this.memberSubject = item
      studySubjectUser_getListByStudySubjectId({studySubjectId:item.id}).then(response => {
        let memberList = []
        for(let i=0;i<response.data.length;i++){
          memberList.push({
            id:response.data[i].userId,
            name:response.data[i].userName,
            nameEn:response.data[i].userNameEn,
          })
        }
        this.$refs.selectSubjectDeptUserMultipleDialog.show(memberList)
      }).finally(()=>{
      });
    },
    changeMember(val){
      let postList = []
      if(val.length>0){
        for(let i=0;i<val.length;i++){
          let item = val[i]
          postList.push({
            userId:item.id,
            userName:item.name,
            userNameEn:item.nameEn,
          })
        }
      }
      this.memberList = postList
      studySubjectUser_save({
        studySubjectId:this.memberSubject.id,
        subjectUserList:this.memberList,
        sign:{}
      }).then(() => {
        this.$refs.selectSubjectDeptUserMultipleDialog.close()
        this.signType = 'member'
        this.$refs.subjectSignRef.show(this.$t('page.business.study.study.rybg'),this.$t('page.business.study.study.rybg'))
      }).catch((e) => {
      }).finally(() => {
      })
      
    },

    doChangeMember(sign){
      this.$modal.loading()
      studySubjectUser_save({
        studySubjectId:this.memberSubject.id,
        subjectUserList:this.memberList,
        sign:sign
      }).then(() => {
        this.$refs.subjectSignRef.cancel()
      }).finally(() => {
        this.$modal.closeLoading()
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.study-subject {
  .subject-top {
    background: #f0f7ff;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    border-top: 3px solid #409eff;
    padding: 20px 0;
    text-align: center;
    color: #409eff;
    font-weight: bold;
  }
  .subject-study{
    background: #fafcff;
    padding: 20px;
    color: #666666;
    position: relative;
    .study-info{
      margin-bottom: 20px;
      span{
        color: #777;
      }
      &:last-child{
        margin-bottom: 0;
      }
    }
  }
  .subject-operate{
    margin: 20px 0;
    display: flex;
    flex-direction: row;
    align-items: center;
    .operate-img{
      flex-shrink: 0;
      height: 15px;
      background: #3178ff;
      width: 3px;
    }
    .operate-left{
      flex-shrink: 0;
      font-weight: bold;
      padding-left: 10px;
    }
    .operate-right{
      flex-grow: 1;
      text-align: right;
      .operate-icon{
        cursor: pointer;
      }
    }
  }
  .subject-content{
    .subject-item{
      margin-bottom: 10px;
      padding: 10px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      background: #f9fafc;
      border-radius: 5px;
      cursor: pointer;
      &.active{
        border: 1px solid #47a1ff;
      }
      .subject-item-name{
        color: #777;
      }
      .subject-item-add{

      }
    }
  }
}
.subject-table-box{
  display: flex;
  flex-direction: row;
  align-items: center;
  .subject-table-left{
    flex-shrink: 0;
    width: 60%;
  }
  .subject-table-right{
    flex-grow: 1;
    margin-left: 5px;
  }
}
</style>
