<template>
  <div class="sign-body">
    <span class="sign-title-2"> 批量开通申请表</span>
    <div class="sign-content-box">
      <el-row  :gutter="24" align="center" >
          <el-col :span="9">
            <span style="color: #909399;font-size: 1rem;">信用统一代码:</span>
            <el-button  type="text" @click="editCompany" > {{info.companyNo}} </el-button>
          </el-col>
          <el-col :span="9">
             <span style="color: #909399;font-size: 1rem;">邮件地址:</span>
             <el-button  type="text"  @click="editCompany" >{{info.email}}</el-button>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" class="el-icon-plus"  @click="addNewUser">
              添加用户
            </el-button>
          </el-col>
      </el-row>

      <el-table v-loading="listLoading" :data="list.slice( page*size-size, page*size)" border fit highlight-current-row>
          <el-table-column label="姓名" align="center" prop="nickname" />
          <el-table-column label="手机号" align="center" prop="phone" />
          <el-table-column label="最高学历" align="center" prop="education" />
          <el-table-column label="岗位" align="center" prop="courseName" />
          <el-table-column label="年度" align="center" prop="nd" />
          <el-table-column label="证书编号" align="center" prop="rzCode" />
          <el-table-column label="操作" fixed="right" align="center" width="120">
              <template slot-scope="{row}">
                <el-button @click="editRow( row )" type="text" size="small">修改</el-button>
                <el-button @click="deleteRow( row )" type="text" size="small" style="color: brown;">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
      </el-table>

      <el-pagination @current-change="handleCurrentChange" :current-page="page" :page-size="size"
        layout="total, prev,pager, next" :total="list.length">
      </el-pagination>


      <el-dialog title="修改企业信息" center :visible.sync="updateCompanyDialog" width="500px">
        	<el-form :model="info" :rules="rules2" label-width="120px" ref="updateCompanyDialog" >
        		<el-form-item label="信用统一代码" prop="companyNo" >
        			<el-input v-model="info.companyNo" type="text" style="width: 250px;" />
        		</el-form-item>

            <el-form-item label="邮件地址" prop="email" >
            	<el-input v-model="info.email" type="text" style="width: 250px;" />
            </el-form-item>
        	</el-form>
          <div class="dialog-footer" slot="footer">
          	<el-button @click="updateCompanyDialog = false">取 消</el-button>
          	<el-button @click="doEditCompany()" type="primary">确 定</el-button>
          </div>
        </el-dialog>
      </div>

      <el-dialog title="选择证书" center :visible.sync="selectRzCodeDialog" width="80%">
        	<el-table v-loading="listLoading" :data="recodeList" border fit highlight-current-row>
        	    <el-table-column label="证书编号" align="center" prop="certificateNum" />
              <el-table-column label="岗位类型" align="center" prop="certificateType" />
              <el-table-column label="岗位名称" align="center" prop="positionName" />
        	    <el-table-column label="发证机关" align="center" prop="certificateOrgan" />
        	    <el-table-column label="证书状态" align="center" prop="certificateStatus" />
        	    <el-table-column label="有效期" fixed="right" align="center" >
        	        <template slot-scope="{row}">
                    <span>{{row.startTime}}-{{row.endTime}}</span>
        	        </template>
        	      </el-table-column>
        	    <el-table-column label="操作" fixed="right" align="center">
        	        <template slot-scope="{row}">
        	          <el-button @click="selectRzCode( row )" type="text" size="small">选择</el-button>
        	        </template>
        	      </el-table-column>
        	    </el-table>
        	</el-table>
      </el-dialog>


      <el-dialog title="添加用户" center :visible.sync="addUserDialog" width="520px" :close-on-click-modal="false">
      	<el-form :model="form" :rules="rules" label-width="120px" ref="addUserDialog" >
          <el-form-item label="用户名字" prop="nickname">
      			<el-input v-model="form.nickname" type="text" style="width: 300px;" name="nickname" autocomplete="on" />
      		</el-form-item>
      		<el-form-item label="身份证号" prop="cardId" >
      			<el-input v-model="form.cardId" type="text" style="width: 300px;" name="cardId" autocomplete="on"/>
      		</el-form-item>
          <el-form-item label="证书编号" prop="rzCode" >
          	<el-input v-model="form.rzCode" type="text" style="width: 230px;" />
            <el-button style="width: 70px;" type="primary" @click="reloadRzCode" :disabled="form.cardId.length!=18 || !form.nickname" >查询</el-button>
          </el-form-item>
          <el-form-item label="最高学历" prop="education" >
            <el-select  v-model="form.education" style="width: 300px;" >
            	<el-option v-for="item in educationList" :value="item" :label="item" :key="item"/>
            </el-select>
          </el-form-item>
      		<el-form-item label="手机号码" prop="phone" >
      			<el-input v-model="form.phone" type="text" style="width: 300px;" name="phone"  autocomplete="on" />
      		</el-form-item>
      		<el-form-item label="选择岗位" prop="courseId">
      			<el-select  v-model="form.courseId" style="width: 300px;" >
              <el-option  :value="0" label="选择课程" />
      				<el-option v-for="item in courseList" :value="item.courseId" :label="item.courseName+'|'+item.nd" :key="item.id"/>
      			</el-select>
      		</el-form-item>
      	</el-form>
        <div class="dialog-footer" slot="footer">
        	<el-button @click="closeAddUserDialog()">取 消</el-button>
        	<el-button @click="doAddUser()" type="primary">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import {
  httpServer
} from "@/components/httpServer/httpServer.js";
import { MessageBox } from "element-ui";
  const defaultForm = {
      id:0,
      cardId:'',
      nickname:'',
      email:'',
      phone:'',
      courseId: 0,
      education:'',
      rzCode: ''
  };
  export default {
    data() {
      return {
        param: {
          taskId: 0,
          secret: ''
        },
        info:{
          company:'',
          email:'',
          companyNo:''
        },
        educationList: window.baseConfig.educationList,
        listLoading: false,
        addUserDialog: false,
        updateCompanyDialog: false,
        page: 1,
        size: 10,
        list: [],
        courseList: [],
        selectRzCodeDialog: false,
        recodeList:[],
        form: Object.assign({}, defaultForm),
        rules: {
          nickname: [{required: true, message: "请输入名字", trigger: "blur", min: 2 }],
          education: [{ required: true, message: "请选择学历", trigger: "blur"}],
          cardId: [
            { required: true, message: '请输入身份证号码', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (!value) {
                  return callback(new Error('请输入身份证号码'));
                }
                const cleanValue = value.replace(/[\s()]/g, '').toUpperCase();
                const mainlandReg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
                const hkReg = /^(?:C(?:\d{8}|[A-HJ-NP-Z]\d{7})|[HM](?:\d{10}|\d{8}))$/;
                if (mainlandReg.test(cleanValue) || hkReg.test(cleanValue)) {
                  callback();
                } else {
                  callback(new Error('请输入正确的大陆身份证（18位）或香港身份证（如 A1234567）'));
                }
              },
              trigger: 'blur'
            }
          ],
          phone: [ { required: true, message: "请输入手机号", trigger: "blur", min: 11, max:11  }],
          courseId: [ { required: true, message: "请选择岗位", trigger: "blur" }]
        },
        rules2: {
          companyNo: [{required: true, message: "请输入信用统一代码", trigger: "blur", min: 2 }],
          email: [{ required: true, message: "请输入邮箱地址", trigger: "blur", min: 6 }],
        }
      }
    },
    methods: {
      gotoDetail() {
        let param = this.param;
        httpServer("User.GetOpenCourseList", param).then(res => {
          if (res.code != 200) return;
          this.info =  res.data.info||{}
          this.list = res.data.list || []
          this.courseList = res.data.courseList||[]
        })
      },
      reloadRzCode(){
        let {nickname,cardId} = this.form;
        if( !nickname || cardId.length <15 || cardId.length> 18){
          this.$message({message:'请输入大陆身份证（15-18位）'})
          return
        }
        httpServer("User.ReLoadRzCode", {nickname,cardId}).then( res=>{
          if( res.code != 200) return;
          this.recodeList = res.data;
          this.selectRzCodeDialog = true;
        })
      },
      closeAddUserDialog(){
        this.addUserDialog = false;
        this.$refs["ddUserDialog"] && this.$refs["ddUserDialog"].reseFields();
      },
      selectRzCode(row){
        this.form.rzCode = row.certificateNum||''
        this.selectRzCodeDialog = false;
      },
      editCompany(){
          this.updateCompanyDialog = true
      },
      doAddUser(){
        let cardId = this.form.cardId;
        this.$refs["addUserDialog"].validate((valid) => {
          if (!valid) return;
          let param = Object.assign({}, this.form, this.param);
          httpServer("User.AddOpenCourseInfo", param).then( res=>{
            if (res.code != 200) return;
            this.addUserDialog = false;
            this.$message.successMsg("申请完成", 3)
            this.gotoDetail();
          })
        })
      },
      doEditCompany(){
        this.$refs["updateCompanyDialog"].validate((valid) => {
          if (!valid) return;
          let param = Object.assign({}, this.info, this.param);
          httpServer("User.UpdateOpenCourseTask", param).then( res=>{
            if (res.code != 200) return;
            this.updateCompanyDialog = false;
            this.$message.successMsg("更新成功", 2)
          })
        })
      },
      doDeleteUser(row, cb){
        let param = Object.assign({}, {id:row.id}, this.param);
        httpServer("User.DelOpenCourseInfo", param).then( res=>{
          if (res.code != 200) return;
          this.$message.successMsg("删除完成", 2)
          cb&&cb();
          this.gotoDetail();
        })
      },
      editRow(row){
        this.form = Object.assign(this.form, row);
        this.addUserDialog = true
      },
      deleteRow(row){
        let that = this
        MessageBox({
          title: "删除提醒",
          message: "删除动作不可恢复，请确认是否删除",
          showCancelButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          beforeClose: (action, instance, done) => {
            if (action === "confirm") {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = '提交中...';
              that.doDeleteUser(row, done);
              done();
              instance.confirmButtonLoading = false;
              that.addUserDialog = false;
            } else{
              done();
            }
          }
        })
      },
      addNewUser(){
        this.form = Object.assign(this.form, defaultForm);
        if(!this.info.email){
          this.$message.successMsg("请先补充企业邮箱地址", 3)
          return;
        }
        this.addUserDialog = true
      },
      handleCurrentChange: function(page) {
        this.page = page
      }
    },
    created() {
      this.param.taskId = +this.$route.query.id || '';
      this.param.secret = this.$route.query.secret || '';
      if (this.param.taskId && this.param.secret) {
        this.gotoDetail();
      }
    }
  }
</script>
<style>
  @import url("./index.css");
</style>
