<template>
  <div class="app-warp">
    <div class="detail-structure">
      <el-page-header v-if="parentObj.TYPE === 'add'" content="新建培训任务" @back="goBack"/>
      <div class="detail-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="160px">
          <el-row>
            <el-col :span="24">
              <div class="level-title">
                <h1>基本信息</h1>
              </div>
            </el-col>
            <el-col :span="enterpriseList.length > 0 ? 12 : 10">
              <el-form-item label="培训企业" prop="ENTERPRISE_ID">
                <el-select v-model="form.ENTERPRISE_ID" :disabled="parentObj.STATE !== ''" style="width: 100%;" @change="getDict">
                  <el-option v-for="item in enterpriseList" :key="item.ENTERPRISE_ID" :value="item.ENTERPRISE_ID" :label="item.ENTERPRISE_NAME"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="enterpriseList.length === 0" :span="2" style="padding-left: 20px">
              <div>
                <el-button type="primary" @click="$router.push('/train_customers/cover_training_institution_account')">新建企业</el-button>
              </div>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班级名称" prop="NAME">
                <el-input v-model="form.NAME" :disabled="parentObj.STATE !== '1' && parentObj.STATE !== ''" placeholder="请输入班级名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培训日期" prop="TIME">
                <el-date-picker
                  :disabled="parentObj.STATE !== '1' && parentObj.STATE !== ''"
                  v-model="form.TIME"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期" />
              </el-form-item>
            </el-col>
            <template v-if="form.ENTERPRISE_ID">
              <el-col :span="12">
                <el-form-item label="行业类型" prop="_INDUSTRY_ALL_NAME">
                  <el-input v-model="form._INDUSTRY_ALL_NAME" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="属地" prop="POSSESSION">
                  <el-input v-model="form.POSSESSION_NAME" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="记录人员" prop="RECORDOR">
                  <el-input v-model="form.RECORDOR_NAME" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="考核人员" prop="ASSESSOR">
                  <el-input v-model="form.ASSESSOR_NAME" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="安全管理部门负责人" prop="SAFETYDEPTOR">
                  <el-input v-model="form.SAFETYDEPTOR_NAME" disabled/>
                </el-form-item>
              </el-col>
            </template>
            <el-col :span="12">
              <el-form-item label="负责人" prop="PRINCIPAL">
                <el-input v-model="form.PRINCIPAL" :disabled="parentObj.STATE !== '1' && parentObj.STATE !== ''" placeholder="请输入负责人"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="负责人电话" prop="PRINCIPAL_PHONE">
                <el-input v-model="form.PRINCIPAL_PHONE" :disabled="parentObj.STATE !== '1' && parentObj.STATE !== ''" placeholder="请输入负责人电话"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培训类型" prop="trainAllName">
                <el-input
                  :disabled="parentObj.STATE !== '1' && parentObj.STATE !== ''"
                  v-model="form.trainAllName"
                  readonly
                  maxlength="255"
                  placeholder="请选择培训类型..."
                  title="培训类型"
                  @click.native="dialogFormVisible = true"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <div class="level-title">
                <h1>基本设置</h1>
              </div>
            </el-col>
            <el-col :span="24">
              <el-form-item label="是否开启问卷调查" prop="ISQUESTIONNAIRE">
                <el-radio-group v-model="form.ISQUESTIONNAIRE" :disabled="parentObj.STATE !== '1' && parentObj.STATE !== ''" >
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
                <span style="padding-left: 5px">开启问卷调查后,学员学完课程后会被随机抽取进行调查评问卷的填写，结果会记录在《综合考评报告》档案中。</span>
              </el-form-item>
            </el-col>
            <el-col v-if="form.ISQUESTIONNAIRE === '1'" :span="12">
              <el-form-item label="调查问卷" prop="SURVEY_ID">
                <el-select v-model="form.SURVEY_ID" :disabled="parentObj.STATE !== '1' && parentObj.STATE !== ''" placeholder="请选择" style="width: 100%;">
                  <el-option v-for="item in surveyList" :key="item.SURVEY_ID" :label="item.TITLE" :value="item.SURVEY_ID"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="是否开启考试" prop="EXAMINATION">
                <el-radio-group v-model="form.EXAMINATION" :disabled="parentObj.STATE !== '1' && parentObj.STATE !== ''">
                  <el-radio :label= "1">是</el-radio>
                  <el-radio :label= "0">否</el-radio>
                </el-radio-group>
                <span style="padding-left: 5px">不考试的班级，学员学习完所有课程，即为完成学业。</span>
              </el-form-item>
            </el-col>
            <el-col v-if="form.EXAMINATION == 1" :span="24" prop="NUMBEROFEXAMS">
              <el-form-item label="考试次数" prop="NUMBEROFEXAMS" >
                <el-input-number v-model="form.NUMBEROFEXAMS" :disabled="parentObj.STATE !== '1' && parentObj.STATE !== ''" :min="1" :max="2147483600" label="考试次数"/>
                <el-button v-show="parentObj.STATE !== '1' && parentObj.STATE !== '' && parentObj.STATE !== '6'" type="primary" @click="modifyExamTimes">修改考试次数</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="是否人脸识别" prop="ISFACE">
                <el-radio-group v-model="form.ISFACE" :disabled="parentObj.STATE !== '1' && parentObj.STATE !== ''">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item v-if="form.EXAMINATION == 1" label="是否效果评估" prop="ISSTRENGTHEN">
                <el-radio-group v-model="form.ISSTRENGTHEN" :disabled="parentObj.STATE !== '1' && parentObj.STATE !== ''">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="detail_foot">
          <el-button v-if="parentObj.STATE === '' || parentObj.STATE === '1'" type="primary" @click="confirm">
            {{ parentObj.TYPE === 'add' ? '下一步' : '保存' }}
          </el-button>
          <el-button icon="el-icon-arrow-left" @click="goBack">返回</el-button>
        </div>
      </div>
      <trainingTypeDialog :dialog-form-visible.sync="dialogFormVisible" :industry-show="false" @confirm="trainingTypeDialogConfirm"/>
    </div>
    <el-dialog :visible.sync="modifyExamVisible" title="修改班级中的考试次数" width="30%">
      <el-form ref="examForm" :model="examForm" :rules="examRules">
        <el-form-item label="原考试次数" label-width="100px">
          <el-input v-model="examForm.source" type="number" disabled autocomplete="off"/>
        </el-form-item>
        <el-form-item label="新考试次数" prop="target" label-width="100px">
          <el-input-number v-model="examForm.target" :min="examForm.source + 1" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyExamVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyExamTimesConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import trainingTypeDialog from '@/components/trainingTypeDialog'
import { requestFN } from '@/utils/request'
export default {
  components: {
    trainingTypeDialog
  },
  data() {
    return {
      form: {
        NUMBEROFEXAMS: 1,
        EXAMINATION: 1,
        _INDUSTRY_ALL_NAME: '',
        INDUSTRY_END_ID: '',
        _INDUSTRY_END_ID: '',
        _INDUSTRY_ALL_TYPE: '',
        NAME: '',
        POSSESSION: [],
        POSSESSION_NAME: '',
        TIME: [],
        PRINCIPAL: '',
        PRINCIPAL_PHONE: '',
        TRAINERS_NUMBER: '',
        ISSUE: '',
        EXAM_TIME: '',
        ISQUESTIONNAIRE: '0',
        SAMPLINGNUMBER: '0',
        ISFACE: '1',
        RECORDOR: '',
        RECORDOR_NAME: '',
        ASSESSOR: '',
        ASSESSOR_NAME: '',
        SAFETYDEPTOR: '',
        SAFETYDEPTOR_NAME: '',
        ENTERPRISE_ID: '',
        ISSTRENGTHEN: '1'
      },
      examForm: {
        source: 0,
        target: ''
      },
      examRules: {
        target: [
          { required: true, message: '请填写新的考试次数', trigger: 'blur' }
        ]
      },
      rules: {
        _INDUSTRY_ALL_NAME: [
          { required: true, message: '请输入行业类型', trigger: 'blur' }
        ],
        NAME: [
          { required: true, message: '请输入班级名称', trigger: 'blur' }
        ],
        POSSESSION: [
          { required: true, message: '请选择行政区划', trigger: 'blur' }
        ],
        TIME: [
          { required: true, message: '请选择有效日期', trigger: 'blur' }
        ],
        PRINCIPAL: [
          { required: true, message: '请填写负责人', trigger: 'blur' }
        ],
        PRINCIPAL_PHONE: [
          { required: true, message: '请填写负责人电话', trigger: 'blur' },
          {
            pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        ISQUESTIONNAIRE: [
          { required: true, message: '请选择是否开启问卷调查', trigger: 'blur' }
        ],
        EXAMINATION: [
          { required: true, message: '请选择是否考试', trigger: 'blur' }
        ],
        NUMBEROFEXAMS: [
          { required: true, message: '请填写考试次数', trigger: 'blur' }
        ],
        SURVEY_ID: [
          { required: true, message: '请选择调查问卷', trigger: 'blur' }
        ],
        trainAllName: [
          { required: true, message: '请选择培训类型', trigger: 'change' }
        ],
        RECORDOR: [
          { required: true, message: '请维护记录人员', trigger: 'change' }
        ],
        ASSESSOR: [
          { required: true, message: '请维护考核人员', trigger: 'change' }
        ],
        SAFETYDEPTOR: [
          { required: true, message: '请维护安全管理部门负责人', trigger: 'change' }
        ],
        ENTERPRISE_ID: [
          { required: true, message: '请选择培训企业', trigger: 'blur' }
        ],
        ISFACE: [
          { required: true, message: '请选择是否人脸识别', trigger: 'blur' }
        ],
        ISSTRENGTHEN: [
          { required: true, message: '请选择是否加强学习', trigger: 'blur' }
        ]
      },
      showInfoHeader: true,
      areaList: [],
      surveyList: [],
      enterpriseList: [],
      recordingPersonnelList: [],
      headOfSafetyManagementDepartmentList: [],
      assessorsList: [],
      areaProps: {
        lazy: true,
        lazyLoad: this.lazyLoad,
        value: 'numValue',
        id: 'id',
        label: 'label',
        children: 'children',
        checkStrictly: true
      },
      dialogFormVisible: false,
      modifyExamVisible: false
    }
  },
  inject: ['parentObj', 'setActiveName', 'setCLASS_ID', 'setENTERPRISE_ID'],
  watch: {
    'form.NUMBEROFEXAMS': {
      handler(newVal, oldVle) {
      }
    }
  },
  created() {
    this.getEnterprise()
    this.getSurvey()
    if (this.parentObj.CLASS_ID) {
      this.getData()
    }

    this.getDictByDicId('e725d2a91b8248f4b8f49889038df7de').then(data => {
      this.areaList = data
    })
  },
  methods: {
    getEnterprise() {
      requestFN(
        'corpEnterpriseContact/listByCorp',
        {
          INSERVICE: '1',
          STATE: this.parentObj.STATE
        }
      ).then((data) => {
        this.enterpriseList = data.varList
      }).catch((e) => {
      })
    },
    getData() {
      requestFN('/class/goEdit', {
        CLASS_ID: this.parentObj.CLASS_ID
      }).then(res => {
        this.form = res.pd
        // this.$set(this.form, 'POSSESSION', [res.pd.PROVINCE, res.pd.CITY, res.pd.COUNTY])
        this.$set(this.form, 'TIME', [res.pd.START_TIME, res.pd.END_TIME])
        const pn = res.pd.POSTTYPE_NAME ? '-' + res.pd.POSTTYPE_NAME : ''
        const iname = res.pd.INDUSTRY3_NAME ? '-' + res.pd.INDUSTRY3_NAME : ''
        const tlName = res.pd.TRAINLEVEL_NAME ? '-' + res.pd.TRAINLEVEL_NAME : ''
        this.form.trainAllName = res.pd.TRAININGTYPE_NAME + pn + iname + tlName
        if (res.pd.posOption && res.pd.posOption.length > 0) {
          this.areaList = res.pd.posOption
        }
        this.form.ENTERPRISE_ID = res.pd.ENTERPRISE_ID
        this.getDict()
      })
    },
    lazyLoad(nodeValue, resolve) {
      if (nodeValue.data && (!nodeValue.children || nodeValue.children.length === 0)) {
        this.getDictByDicId(nodeValue.data.id, nodeValue.level).then(data => {
          resolve(data)
        })
      } else {
        resolve(null)
      }
    },
    getDictByDicId(dicId, level) {
      var dicListVal = []
      return new Promise((resolve) => {
        let id = ''
        if (!dicId) {
          id = '0'
        } else {
          id = dicId
        }
        requestFN(
          '/dictionaries/getHebeiPossession',
          {
            DICTIONARIES_ID: id,
            LEVEL: level
          }
        ).then((data) => {
          if (data.list.length > 0) {
            dicListVal = data.list.map((e) => {
              return {
                value: e.DICTIONARIES_ID.toString(),
                numValue: e.BIANMA.toString(),
                label: e.NAME,
                id: e.DICTIONARIES_ID,
                leaf: level > 1
              }
            })
          } else {
            dicListVal = undefined
          }
          return resolve(dicListVal)
        }).catch((e) => {
        })
      })
    },
    getSurvey() {
      requestFN(
        '/survey/listAll',
        {
        }
      ).then((data) => {
        this.surveyList = data.varList
      }).catch((e) => {
      })
    },
    getDict() {
      for (let i = 0; i < this.enterpriseList.length; i++) {
        if (this.enterpriseList[i].ENTERPRISE_ID === this.form.ENTERPRISE_ID) {
          this.form._INDUSTRY_ALL_NAME = this.enterpriseList[i].INDUSTRY_ALL_NAME

          this.form.INDUSTRY_END_ID = this.enterpriseList[i].INDUSTRY_END_ID
          this.form._INDUSTRY_END_ID = this.enterpriseList[i].INDUSTRY_END_ID
          console.log(this.form.INDUSTRY_END_ID)

          this.form._INDUSTRY_ALL_TYPE = this.enterpriseList[i].INDUSTRY_ALL_TYPE
          break
        }
      }
      requestFN(
        'trainedusersign/listByEnt',
        {
          ENTERPRISE_ID: this.form.ENTERPRISE_ID,
          USERSIGNTYPE: '854c77daf3734384807a638dfafe04d5'
        }
      ).then((data) => {
        this.recordingPersonnelList = data.varList
        this.$set(this.form, 'RECORDOR', '')
        this.$set(this.form, 'RECORDOR_NAME', '')
        this.form.RECORDOR = data.varList[0].USERSIGNID
        this.form.RECORDOR_NAME = data.varList[0].USERNAME
      }).catch((e) => {
      })
      requestFN(
        'trainedusersign/listByEnt',
        {
          ENTERPRISE_ID: this.form.ENTERPRISE_ID,
          USERSIGNTYPE: '5f4794189cf24fc2a7e12fa47b70139e'
        }
      ).then((data) => {
        this.headOfSafetyManagementDepartmentList = data.varList
        this.$set(this.form, 'SAFETYDEPTOR', '')
        this.$set(this.form, 'SAFETYDEPTOR_NAME', '')
        this.$set(this.form, 'SAFETYDEPTOR', data.varList[0].USERSIGNID)
        this.$set(this.form, 'SAFETYDEPTOR_NAME', data.varList[0].USERNAME)
      }).catch((e) => {
      })
      requestFN(
        'trainedusersign/listByEnt',
        {
          ENTERPRISE_ID: this.form.ENTERPRISE_ID,
          USERSIGNTYPE: 'f2726f92987d4f77be1c3f0460669418'
        }
      ).then((data) => {
        this.assessorsList = data.varList
        this.$set(this.form, 'ASSESSOR', '')
        this.$set(this.form, 'ASSESSOR_NAME', '')
        this.$set(this.form, 'ASSESSOR', data.varList[0].USERSIGNID)
        this.$set(this.form, 'ASSESSOR_NAME', data.varList[0].USERNAME)
      }).catch((e) => {
      })
      // 获取企业属地
      requestFN(
        '/enterprises/getAreaByEid',
        {
          ENTERPRISE_ID: this.form.ENTERPRISE_ID
        }
      ).then((data) => {
        this.$set(this.form, 'POSSESSION', data.varList.POSSESSION.split(','))
        this.$set(this.form, 'POSSESSION_NAME', data.varList.AREA)
      }).catch((e) => {
      })
    },
    trainingTypeDialogConfirm(e) {
      Object.keys(e).forEach(key => {
        this.$set(this.form, key, e[key])
      })
    },
    // 修改考试次数
    modifyExamTimes() {
      this.modifyExamVisible = true
      this.examForm.source = this.form.NUMBEROFEXAMS
    },
    modifyExamTimesConfirm() {
      this.$refs.examForm.validate((valid) => {
        if (valid) {
          this.$confirm('确定要修改该班级的考试次数吗？考试已通过的学员不受影响', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            requestFN('/class/editNumberofexams',
              {
                NUMBEROFEXAMS: this.examForm.target,
                CLASS_ID: this.parentObj.CLASS_ID
              }
            ).then(res => {
              this.modifyExamVisible = false
              this.$message.success('修改成功')
              this.form.NUMBEROFEXAMS = this.examForm.target
              this.examForm.target = this.examForm.target + 1
              location.reload()
            }).catch()
          }).catch(() => {
            this.$message.error('修改失败')
          })
        }
      })
    },
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.form.TRAINTYPE) {
            this.$message.error('培训类型未选择')
            return
          }
          if (!this.form.POSTTYPE) {
            this.$message.error('岗位类型未选择')
            return
          }
          let url = ''

          this.form.ISSTRENGTHEN = this.form.EXAMINATION === 1 ? this.form.ISSTRENGTHEN : '0'
          const params = {
            ...this.form,
            INDUSTRY_ALL_NAME: this.form._INDUSTRY_ALL_NAME,
            INDUSTRY_ALL_TYPE: this.form._INDUSTRY_ALL_TYPE,
            INDUSTRY_END_ID: this.form._INDUSTRY_END_ID,
            START_TIME: this.form.TIME[0],
            END_TIME: this.form.TIME[1],
            PROVINCE: this.form.POSSESSION[0],
            EXAMINATION: this.form.EXAMINATION,
            CITY: this.form.POSSESSION[1],
            COUNTY: this.form.POSSESSION[2]
          }
          console.info(params.ISSTRENGTHEN)
          if (this.parentObj.CLASS_ID) {
            url = '/class/edit'
            params.CLASS_ID = this.parentObj.CLASS_ID
          } else {
            url = '/class/add'
          }
          requestFN(url, params).then(res => {
            if (res.message) {
              this.$message({
                message: res.message,
                type: 'warning'
              })
              return
            } else {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
            }
            if (this.parentObj.TYPE === 'add') {
              this.setCLASS_ID(res.CLASS_ID)
              this.setENTERPRISE_ID(res.ENTERPRISE_ID)
              this.setActiveName('StudentList')
            }
          })
        } else {
          this.$message({
            message: '请检查输入项',
            type: 'warning'
          })
          return false
        }
      })
    },
    goBack() {
      this.setActiveName('List')
    }
  }
}
</script>

<style scoped>

</style>
