<template>
  <div class="page-container researchGroupManage-addPage">
    <div class="page-top-title-box">
      <p class="page-top-title-name-p">{{addForm.id?'编辑课题组':'新增课题组'}}</p>
      <p class="page-top-title-out-p" @click="backPage">返回</p>
      <p class="page-top-title-add-p" @click="submitForm">提交</p>
    </div>
    <div class="content-box scrollbar-box">
      <el-form class="add-form-box" :model="addForm" ref="form" :rules="rules" label-width="160px">
        <div style="display: flex">
          <el-form-item label="课题名称：" prop="topicName">
            <el-input v-model="addForm.topicName" placeholder="请输入课题名称" maxLength="20" style="width:1260px;"></el-input>
          </el-form-item>
          <el-form-item label="" prop="isStart" class="page-switch" label-width="40px">
            <el-switch
              :active-value="true"
              :inactive-value="false"
              active-color="#0183FA"
              inactive-color="#999"
              v-model="addForm.isStart"
              active-text="启用"
              inactive-text="停用"
            ></el-switch>
          </el-form-item>
        </div>
        <div style="display: flex">
          <el-form-item label="课题负责人：" prop="userId">
            <el-select
              style="width:600px;"
              v-model="addForm.userId"
              filterable
              remote
              reserve-keyword
              @change="userChange"
              placeholder="搜索选择课题负责人"
              :remote-method="userSelectList">
              <el-option
                v-for="item in optionsUser"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号码：" label-width="170px" prop="userPhone">
            <el-input
              style="width:600px;"
              maxlength="11"
              v-model="addForm.userPhone"
              placeholder="未填写"
              onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"
            />
          </el-form-item>
        </div>
        <div class="add-form-title-box">
          <p class="left-num-p">成员列表（{{maxUserNum}}）</p>
          <p class="null-p"></p>
          <p class="page-submit-common-style-button right-button-p"
             @click="tableButton(1)"
          >+  添加成员</p>
        </div>
        <div class="page-content-box">
          <el-table class="table-box" border :data="addForm.memberList">
            <el-table-column label="序号" prop="name" width="50" type="index" show-overflow-tooltip/>
            <el-table-column label="姓名" prop="userName" show-overflow-tooltip/>
            <el-table-column label="联系电话" prop="mobile" width="230" show-overflow-tooltip/>
            <el-table-column label="所属部门" prop="deptName" width="470" show-overflow-tooltip/>
            <el-table-column label="状态" prop="isStart" width="200" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-switch
                  class="switch captcha-img"
                  :active-value="true"
                  :inactive-value="false"
                  active-color="#0183FA"
                  inactive-color="#999"
                  v-model="scope.row.isStart"
                  active-text="启用"
                  inactive-text="停用"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" show-overflow-tooltip>
              <template slot-scope="scope">
                <div class="table-button-box">
                  <p class="table-button-null"></p>
                  <p class="table-button-p"
                     @click="tableButton(3,scope.$index)"
                  >删除</p>
                  <p class="table-button-null"></p>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!--<pagination :page-sizes="[20, 30, 40, 50]"-->
                      <!--v-show="total>0"-->
                      <!--:total="total"-->
                      <!--:page.sync="queryParams.page"-->
                      <!--:limit.sync="queryParams.pageSize"-->
                      <!--@pagination="getList"-->
          <!--/>-->
        </div>
      </el-form>
    </div>
    <user-dialog :addDialogData="addDialogData" ref="userDialog"></user-dialog>
  </div>
</template>

<script>
  //import { getDicts } from "@/api/commonality/noPermission";
  //import { systemUserSelect } from "@/api/commonality/permission";
  //import { getInfo } from "@/api/basicsModules/index";

  import { systemTopicDetail,systemTopicAdd,systemTopicEdit } from "@/api/integratedManagement/index";
  import { systemUserDropDateAuthList,systemUserSelectByPage } from "@/api/commonality/permission";
  import userDialog from "./userDialog.vue";
  export default {
    name: 'addPage',
    components: {
      userDialog
    },
    props:{
      propsData:{},
    },
    data(){
      return{
        optionsUser:[],
        addForm:{
          topicName:'',
          isStart:true,
          account:'',
          userId:'',
          userName:'',
          userPhone:'',
          deptName:'',
          deptId:'',
          memberList:[]
        },
        rules:{
          topicName: [
            { required: true, message: "请输入课题名称", trigger: "blur" },
            { required: true, message: "请输入课题名称", validator: this.spaceJudgment, trigger: "blur" }
          ],
          userId: [
            { required: true, message: "搜索选择课题负责人", trigger: "blur" },
            { required: true, message: "搜索选择课题负责人", validator: this.spaceJudgment, trigger: "blur" }
          ],
          userPhone: [
            { required: true, message: "请输入手机号码", trigger: "blur" },
            { validator: this.checkPhone, trigger: 'blur' },
            { required: true, message: "请输入手机号码", validator: this.spaceJudgment, trigger: "blur" }
          ],
        },
        queryParams:{
          page:1,
          pageSize:20,
        },
        //列表数据
        dataList:[],
        //数据数量
        total:0,
        maxUserNum:0,
        //子组件传参
        addDialogData:{},
      }
    },
    created(){
      this.dataInitialization();
    },
    mounted(){

    },
    methods:{
      //初始化
      dataInitialization(){
        if(this.propsData.id){
          this.systemTopicDetail();
        }
      },
      // 返回按钮
      backPage(){
        this.$parent.tableButton(6);
      },
      //查询详情
      systemTopicDetail(){
        systemTopicDetail({id:this.propsData.id}).then(response => {
          let obj = response.data.topic;
          // obj.memberList = response.data.memberList;
          this.userSelectList(obj.userName);
          this.$set(this,'addForm',obj);
          let list = [];
          for(let i=0;i<response.data.memberList.length;i++){
            list.push(response.data.memberList[i].userId)
          }
          this.systemUserSelectByPage(list,response.data.memberList)
        });
      },
      //操作按钮
      tableButton(type,index){
        let self = this;
        if(type == 1){
          //新增
          let list = [];
          for(let i=0;i<self.addForm.memberList.length;i++){
            list.push(self.addForm.memberList[i].userId);
          }
          this.$set(this.addDialogData,'userList',list);
          this.$refs['userDialog'].userDialogOpen();
        }else if(type == 3){
          //删除
          this.$confirm('是否确认删除?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
          }).then(() => {
            self.addForm.memberList.splice(index,1)
          }).catch(() => {});
        }
      },
      /** 提交按钮 */
      submitForm() {
        let self = this;
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(!this.addForm.memberList[0]){
              this.msgError('请添加课题组成员')
              return
            }
            let obj = JSON.parse(JSON.stringify(this.addForm))
            let list = [];
            obj.memberList.forEach((item)=>{
              let minObj = {
                account:item.account,
                userId:item.userId,
                userName:item.userName,
                userPhone:item.userPhone,
                userType:item.userType,
                deptId:item.deptId,
                deptName:item.deptName,
              }
              if(self.propsData.id){
                minObj.topicId = self.propsData.id
                minObj.topicName = self.propsData.topicName
              }
              list.push(minObj);
            })
            obj.memberList = list;
            if(this.propsData.id){
              systemTopicEdit(obj).then(response => {
                this.msgSuccess(response.message)
                this.backPage();
              });
            }else{
              systemTopicAdd(obj).then(response => {
                this.msgSuccess(response.message)
                this.backPage();
              });
            }
          }
        })
      },
      //人员选择
      userChange(val){
        let self = this;
        for(let i=0;i<self.optionsUser.length;i++){
          if(val == self.optionsUser[i].userId){
            this.$set(this.addForm,'userId',self.optionsUser[i].userId);
            this.$set(this.addForm,'account',self.optionsUser[i].account);
            this.$set(this.addForm,'userName',self.optionsUser[i].userName);
            this.$set(this.addForm,'deptId',self.optionsUser[i].deptId);
            this.$set(this.addForm,'deptName',self.optionsUser[i].deptName);
            this.$set(this.addForm,'userPhone',self.optionsUser[i].mobile?self.optionsUser[i].mobile:'');
          }
        }
      },
      //人员查询
      userSelectList(query) {
        if (query !== '' && query.length>1) {
          systemUserDropDateAuthList({"userName":query,'userType':'1'}).then(response => {
            this.$set(this,'optionsUser',response.data);
          });
        } else {
          this.$set(this,'optionsUser',[]);
        }
      },
      //手机号验证
      checkPhone(rule, value, callback) {
        if (!value) {
          return callback(new Error('不能为空'))
        } else {
          const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/
          if (reg.test(value)) {
            callback()
          } else {
            return callback(new Error('请输入正确的手机号码'))
          }
        }
      },
      //接受选中人员
      setUserList(list,dataList){
        let self = this;
        let newList = [];
        for(let o=0;o<dataList.length;o++){
          let num = 0;
          for(let i=0;i<self.addForm.memberList.length;i++){
            if(self.addForm.memberList[i].userId == dataList[o].userId){
              newList.push(self.addForm.memberList[i]);
              num++
            }
          }
          if(num == 0){
            newList.push(dataList[o]);
          }
        }
        this.systemUserSelectByPage(list,newList);
      },
      //处理人员数据
      userDataSet(list,dataList){

      },
      //获取人员列表
      systemUserSelectByPage(list,dataList){
        systemUserSelectByPage({userIds:list[0]?list:['-999999999999999999'],pageSize:100}).then(response => {
          for(let i=0;i<response.data.records.length;i++){
            for(let o=0;o<dataList.length;o++){
              if(response.data.records[i].userId == dataList[o].userId){
                response.data.records[i].isStart = dataList[o].isStart;
              }
            }
          }
          this.$set(this.addForm,'memberList',response.data.records);
          this.$set(this,'maxUserNum',response.data.total);
        });
      },
    },
  }
</script>

<style scoped lang="scss">
  .researchGroupManage-addPage{
    .content-box{
      flex:1;
      display: flex;
      flex-direction: column;
      padding:40px 0 20px;
      overflow: hidden;
      .add-form-box{
        flex:1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        .add-form-title-box{
          padding:20px 52px 20px;
          display: flex;
          .left-num-p{
            line-height:40px;
            font-size:16px;
          }
          .null-p{
            flex:1;
          }
          .right-button-p{
            width:120px;
            margin-right:300px;
          }
        }
        .page-content-box{
          padding:0 52px;
        }
      }
    }
  }
</style>
