<template>
  <el-dialog
    :title="
      `${type ? '详情' : id ? '编辑' : '新增'} - ${dictionaryEscape(
        'jhlx',
        planType
      )}训练计划`
    "
    :visible.sync="dialogVisible"
    custom-class="new-edition-dialog"
    top="3vh"
    width="60%"
    @closed="closed"
    @open="open"
  >
    <el-steps :active="isActive" finish-status="success" simple>
      <el-step title="训练计划数据"></el-step>
      <el-step title="训练使用物资"></el-step>
      <el-step title="参训考生"></el-step>
    </el-steps>

    <el-form
      ref="form"
      :model="form"
      :rules="type == '详情' ? '' : rules"
      label-position="top"
      label-width="auto"
    >
      <el-row
        v-if="isActive == 0"
        :gutter="24"
        style="flex-wrap:wrap"
        type="flex"
      >
        <el-col :span="8">
          <el-form-item label="单位" prop="orgName">
            <el-input
              v-model="form.orgName"
              clearable
              disabled
              placeholder="请输入单位"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年度" prop="year">
            <el-date-picker
              v-model="form.year"
              placeholder="请选择年度"
              style="width: 100%;"
              type="year"
              value-format="yyyy"
              disabled
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="planType == '2'">
          <el-form-item label="季度" prop="quarter">
            <el-select
              disabled
              v-model="form.quarter"
              clearable
              placeholder="请选择季度"
              style="width: 100%;"
            >
              <el-option
                v-for="(item, i) in getDictionaryByCode('jdmc')"
                :key="i"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="planType == '3' || planType == '4'">
          <el-form-item label="月" prop="month">
            <el-input disabled style="width: 100%;" v-model="form.month">
            </el-input
          ></el-form-item>
        </el-col>
        <el-col :span="8" v-if="planType == '4'">
          <el-form-item label="周" prop="week">
            <el-input disabled v-model="form.week" placeholder="请输入周">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="训练课目" prop="subjectId">
            <el-select
              v-model="form.subjectId"
              clearable
              disabled
              placeholder="请选择训练课目"
              style="width:100%"
              @change="selectSubject"
              v-on:click.native="subjectDUsers"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="训练起始日期" prop="startEndTime">
            <el-date-picker
              :disabled="type == '详情'"
              v-model="form.startEndTime"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
              value-format="yyyy-MM-dd"
              clearable
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="教练员" prop="coachId">
            <el-select
              :disabled="type == '详情'"
              v-model="form.coachId"
              filterable
              multiple
              clearable
              placeholder="请选择教练员"
              style="width:100%"
            >
              <el-option
                v-for="item in coachNameList"
                :key="item.fullname"
                :label="item.fullname"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="训练时长" prop="hour">
            <el-input
              v-model="form.hour"
              :disabled="type == '详情'"
              clearable
              placeholder="请输入训练时长"
              @input="formatNums(form.hour)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="岗位" prop="postId">
            <el-select
              v-model="form.postId"
              clearable
              :disabled="type == '详情'"
              multiple
              placeholder="请选择岗位"
              style="width: 100%;"
              @change="changePost"
              v-on:click.native="getPostDialog"
            >
              <el-option
                v-for="(item, i) in postList"
                :key="i"
                :label="item.positionName"
                :value="item.positionId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="专业" prop="majorId">
            <el-select
              v-model="form.majorId"
              filterable
              clearable
              :disabled="type == '详情'"
              placeholder="请选择专业"
              style="width:100%"
            >
              <el-option
                v-for="item in majorVosList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="训练等级" prop="trainLevel">
            <el-select
              v-model="form.trainLevel"
              filterable
              clearable
              placeholder="请选择训练等级"
              :disabled="type == '详情'"
              style="width:100%"
            >
              <el-option
                v-for="item in getDictionaryByCode('xljb')"
                :key="item.name"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="训练场地" prop="spaceId">
            <el-select
              v-model="form.spaceId"
              filterable
              clearable
              :disabled="type == '详情'"
              placeholder="请选择训练场地"
              style="width:100%"
            >
              <el-option
                v-for="item in spaceNameList"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="训练方式" prop="way">
            <el-select
              v-model="form.way"
              filterable
              clearable
              placeholder="请选择训练方式"
              style="width:100%"
              :disabled="type == '详情'"
            >
              <el-option
                v-for="item in getDictionaryByCode('xlfs')"
                :key="item.name"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="训练类别" prop="trainType">
            <el-select
              clearable
              v-model="form.trainType"
              placeholder="请选择训练方式"
              :disabled="type == '详情'"
              style="width:100%"
            >
              <el-option
                v-for="item in getDictionaryByCode('xllb')"
                :key="item.name"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="训练内容及要求" prop="memo">
            <el-input
              v-model="form.memo"
              :autosize="{minRows: 4, maxRows: 8}"
              clearable
              :disabled="type == '详情'"
              placeholder="请输入备注"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isActive == 1" style="flex-wrap:wrap" type="flex">
        <el-col :span="24" style="margin: 10px 0;">
          <el-button
            size="small"
            type="primary"
            v-if="type !== '详情'"
            @click="addCunt"
          >
            添加物资
          </el-button>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="materials">
            <el-table
              :data="form.materials"
              border
              height="300"
              size="medium"
              stripe
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
              ></el-table-column>
              <el-table-column
                label="	消耗指标名称"
                prop="indexName"
              ></el-table-column>
              <el-table-column label="指标类型" prop="type">
                <template v-slot="{row}">
                  {{ dictionaryEscape('zb_type', row.type) }}
                </template>
              </el-table-column>

              <el-table-column label="计量单位" prop="unit"></el-table-column>
              <el-table-column
                label="
    计划使用数量"
                prop="planNumber"
              >
                <template v-slot="{row}">
                  <el-input-number
                    :disabled="type == '详情'"
                    v-model="row.planNumber"
                    :max="row.number"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                v-if="type !== '详情'"
                align="center"
                label="操作"
                prop="fullname"
              >
                <template v-slot="{row}">
                  <el-link type="danger" @click="delIndex(row)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isActive == 2" style="flex-wrap:wrap" type="flex">
        <el-col :span="24" style="margin: 10px 0;">
          <el-button
            size="small"
            type="primary"
            v-if="type !== '详情'"
            @click="getCandidatePerson"
          >
            添加考生
          </el-button>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="userTrainPlans">
            <el-table
              :data="form.userTrainPlans"
              border
              height="300"
              size="medium"
              stripe
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
              ></el-table-column>

              <el-table-column align="center" label="姓名" prop="userName">
                <template v-slot="{row}">
                  {{ row.userName }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="单位" prop="orgName">
                <template v-slot="{row}">
                  {{ row.orgName }}
                </template></el-table-column
              >

              <el-table-column
                v-if="type !== '详情'"
                align="center"
                label="操作"
                prop="fullname"
              >
                <template v-slot="{row}">
                  <el-link type="danger" @click="delUser(row)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button v-if="isActive > 0" type="primary" @click="lastStep"
        >上一步</el-button
      >
      <el-button v-if="isActive < 2" type="primary" @click="nextStep"
        >下一步</el-button
      >
      <el-button
        v-if="isActive == 2 && type !== '详情'"
        :loading="saveLoading"
        type="primary"
        @click="handleSave"
      >
        确 认
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </span>

    <jobs-dialog ref="postData" @getUser="getPost"></jobs-dialog>
    <subjectDialog ref="subjectDialog" @getUser="getUser" />
    <!-- <mianPersonVue ref="mianPersonVue" @getUser="getMainUser" /> -->
    <goodsAndMaterials ref="goodsAndMaterials" @getUser="getMaterials" />
    <candidatePerson ref="candidatePerson" @getUser="getPerson" />
  </el-dialog>
</template>

<script>
import * as examSpaceData from '@/api/examDataMenu/examSafeguardData/examSpaceData.js'
import * as coachApi from '@/api/examination/jlyList.js'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import jobsDialog from '@/components/examDialog/jobsDialog.vue'
import subjectDialog from '@/components/examDialog/subjectDialog.vue'
import * as api from '@/api/examDataMenu/examManagerData/examPlan.js'
import equSysMenu from '@/api/examination/equSysMenu.js'
import moment from 'moment'

import candidatePerson from '@/components/examDialog/candidatePerson.vue'
import goodsAndMaterials from '@/components/examDialog/goodsAndMaterials.vue'

export default {
  name: 'AddEditDialog',
  components: {
    jobsDialog,
    subjectDialog,
    // mianPersonVue,
    goodsAndMaterials,
    candidatePerson
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    rowInfo: {
      type: Object,
      default: () => ({})
    },
    activeTreeItem: {
      type: Object,
      default: () => ({})
    },
    planType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      rules: {
        orgName: [{required: true, message: '请输入单位', trigger: 'blur'}],
        year: [{required: true, message: '请选择年度', trigger: 'change'}],
        startEndTime: [
          {required: true, message: '请选择起始时间', trigger: 'change'}
        ],
        subjectId: [
          {required: true, message: '请选择训练科目', trigger: 'change'}
        ],
        hour: [{required: true, message: '请输入训练时长', trigger: 'blur'}],
        coachId: [{required: true, message: '请选择教练员', trigger: 'blur'}],
        mainUserId: [
          {required: true, message: '请选择主训员', trigger: 'blur'}
        ],
        materials: [
          {required: true, message: '请选择训练物资', trigger: 'blur'}
        ],
        userTrainPlans: [
          {required: true, message: '请选择参训考生', trigger: 'blur'}
        ]
      },
      form: {
        year: moment().format('YYYY'),
        materials: []
      },

      saveLoading: false,
      isActive: 0,
      majorVosList: [], //专业字典
      subjectList: [], //课目字典
      trainLevelList: [], //训练等级字典
      spaceNameList: [], //训练场地字典
      coachNameList: [], //教练员字典
      // mainUserIdList: [], //主训员字典
      postList: []
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('update:value', val)
      }
    },
    id() {
      return this.rowInfo?.id || ''
    },
    type() {
      return this.rowInfo?.type || ''
    }
  },
  created() {},
  methods: {
    getDictionaryByCode,
    dictionaryEscape,

    formatNums(val) {
      let temp = val.toString()
      temp = temp.replace(/。/g, '.')
      temp = temp.replace(/[^\d.]/g, '') //清除"数字"和"."以外的字符
      temp = temp.replace(/^\./g, '') //验证第一个字符是数字
      temp = temp.replace(/\.{2,}/g, '') //只保留第一个, 清除多余的
      temp = temp
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
      temp = temp.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') //只能输入两个小数
      this.form.hour = temp
    },
    delIndex(row) {
      this.form.materials = this.form.materials.filter(item => {
        return item.id !== row.id
      })
    },
    delUser(row) {
      this.form.userTrainPlans = this.form.userTrainPlans.filter(item => {
        return item.id !== row.id
      })
    },
    getMaterials(data) {
      this.$set(
        this.form,
        'materials',
        data.map(item => {
          item.planNumber = 0
          item.indexId = item.id
          item.indexName = item.name

          return item
        })
      )
    },
    getPerson(data) {
      this.$set(
        this.form,
        'userTrainPlans',
        data.map(item => {
          return {
            ...item,
            userName: item.fullname
          }
        })
      )
    },
    getCandidatePerson() {
      this.$refs.candidatePerson.add(this.form.userTrainPlans)
    },
    addCunt() {
      this.$refs.goodsAndMaterials.add(this.form.materials)
    },
    // getMainUser(data) {
    //   this.$set(
    //     this.form,
    //     'mainUserId',
    //     data.map(item => {
    //       return item.id
    //     })
    //   )
    //   this.$set(
    //     this.form,
    //     'mainUserName',
    //     data.map(item => {
    //       return item.fullname
    //     })
    //   )
    //   this.mainUserIdList = data
    // },
    getUser(val) {
      // this.form.subjectId = ''

      this.form.subjectId = val[0].id
      this.form.subjectName = val[0].name

      this.subjectList = val
    },
    selectSubject(val) {
      this.subjectList = []
    },
    getMainPerson() {
      this.$refs.mianPersonVue.add(this.mainUserIdList)
    },
    subjectDUsers() {
      this.$refs.subjectDialog.add(this.subjectList)
    },
    // 获取教练员数据
    async getRoleList() {
      this.coachNameList = await coachApi.getUsersByRoleCode()
    },
    changePost() {
      this.postList = this.postList.filter(item => {
        return this.form.postId.indexOf(item.positionId) > -1
      })
      this.post = this.postList.map(item => {
        item.positionName
      })
    },
    getPostDialog() {
      this.$refs.postData.add(this.postList)
    },
    // 获取岗位
    getPost(data) {
      this.$set(
        this.form,
        'postId',
        data.map(item => item.positionId)
      )
      this.$set(
        this.form,
        'post',
        data.map(item => item.positionName)
      )
      this.postList = data
    },
    // 上一页
    lastStep() {
      this.isActive -= 1
    },
    // 下一页
    nextStep() {
      // this.isActive += 1
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isActive += 1
        } else {
          this.$notify({
            type: 'warning',
            message: '请填写完整训练信息',
            duration: 2000
          })
        }
      })
    },
    // 获取专业数据
    async getMajorList() {
      await equSysMenu.getEqeSys({pageSize: -1}, res => {
        this.majorVosList = res.rows
      })
    },
    // 获取场地数据
    async getLandList() {
      let {rows} = await examSpaceData.tableData({pageSize: -1})
      this.spaceNameList = rows
    },

    // 打开弹层
    open() {
      this.$set(this.form, 'orgName', this.activeTreeItem.name)
      this.$set(this.form, 'orgId', this.activeTreeItem.id)
      this.getMajorList()
      this.getRoleList()
      this.getLandList()
      if (this.id) {
        this.saveLoading = true
        this.getDetail(this.id)
      }
    },

    // 关闭弹层后
    closed() {
      const {rules} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {rules})

      this.$nextTick(_ => {
        this.$refs.form.$el.scrollTop = 0
        this.$refs.form.clearValidate()
      })
    },

    // 获取详情
    async getDetail(id) {
      try {
        let {
          coachId,
          post,
          postId,
          coachName,
          startTime,
          endTime,
          userTrainPlans,
          materials,
          ...form
        } = await api.tableDetail(id)
        let startEndTime = startTime && endTime ? [startTime, endTime] : []
        let userArr = userTrainPlans.map(item => {
          item.fullname = item.userName
          return item
        })

        this.form = {...form, startEndTime}
        this.$set(this.form, 'userTrainPlans', userArr)
        this.subjectList = [
          {
            name: this.form.subjectName,
            id: this.form.subjectId
          }
        ]
        this.$set(this.form, 'coachId', coachId.split(','))
        if (postId) {
          this.$set(this.form, 'post', post.split(','))
          this.$set(this.form, 'postId', postId.split(','))
          this.postList = this.form.postId.map((item, i) => {
            return {
              positionId: item,
              positionName: post.split(',')[i]
            }
          })
        }
        this.$set(this.form, 'coachName', coachName.split(','))
        this.$set(
          this.form,
          'materials',
          materials.map(item => {
            item.id = item.indexId
            item.name = item.indexName
            return item
          })
        )
      } finally {
        this.saveLoading = false
      }
    },

    // 保存
    handleSave() {
      this.$refs.form.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          const myInterFace = this.id ? api.tableEdit : api.tableAdd
          let params = JSON.parse(JSON.stringify(this.form))
          params.materials = params.materials.map(item => {
            delete item.id
            return item
          })
          if (params.spaceId) {
            params.spaceName = this.spaceNameList.filter(item => {
              return item.id == params.spaceId
            })[0].name
          }
          params.userTrainPlans = params.userTrainPlans.map(item => {
            delete item.id
            return item
          })
          params.startTime = params.startEndTime[0]
          params.endTime = params.startEndTime[1]
          params.coachName = this.coachNameList
            .filter(item => {
              return params.coachId.indexOf(item.id) > -1
            })
            .map(item => {
              return item.fullname
            })
            .join(',')
          params.coachId = params.coachId.join(',')
          if (params.postId?.length > 0) {
            params.postId = params.postId.join(',')
            params.post = params.post.join(',')
          }

          params.majorName = this.majorVosList.filter(item => {
            return item.id == params.majorId
          })[0]?.name

          try {
            let {state, message} = await myInterFace({
              ...params,
              planType: this.planType
            })

            if (state) {
              this.$emit('submit', this.id ? 'edit' : 'add')
              message = this.id ? '编辑' : '新增'
              this.$message.success(
                `${dictionaryEscape(
                  'jhlx',
                  this.planType
                )}训练计划${message}成功`
              )
              this.dialogVisible = false
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 10px;
}

::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}

::v-deep .new-edition-dialog .el-dialog__body {
  max-height: 700px;
}
</style>
