<template>
  <el-dialog
    :title="`${type ? '详情' : id ? '编辑' : '新增'} - 补训训练计划`"
    :visible.sync="dialogVisible"
    custom-class="new-edition-dialog"
    width="75%"
    @closed="closed"
    @open="open"
    top="3vh"
  >
    <el-steps :active="isActive" finish-status="success" simple>
      <el-step title="总训练数据"> </el-step>
      <el-step title="参训单位及课目"></el-step>
    </el-steps>

    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="top"
      label-width="auto"
    >
      <el-row
        :gutter="24"
        style="flex-wrap:wrap"
        type="flex"
        v-if="isActive == 0"
      >
        <el-col :span="12">
          <el-form-item label="年度" prop="year">
            <el-date-picker
              :disabled="type == '详情' ? true : false"
              style="width: 100%;"
              v-model="form.year"
              type="year"
              value-format="yyyy"
              placeholder="请选择年度"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="训练起始日期" prop="startEndTime">
            <el-date-picker
              :disabled="type == '详情' ? true : false"
              style="width: 100%;"
              v-model="form.startEndTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker
          ></el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="训练内容及要求" prop="memo">
            <el-input
              :disabled="type == '详情' ? true : false"
              v-model="form.memo"
              :autosize="{minRows: 4, maxRows: 8}"
              clearable
              placeholder="请输入训练内容及要求"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="flex-wrap:wrap" type="flex" v-if="isActive == 1">
        <el-col :span="24" style="margin: 10px 0;">
          <el-button
            v-if="type == '详情' ? false : true"
            type="primary"
            @click="increasePlan"
            size="small"
          >
            添加训练课目</el-button
          >
          <el-button
            type="primary"
            v-if="type == '详情' ? false : true"
            @click="increaseOtherPlan"
            size="small"
          >
            添加其他训练</el-button
          >
        </el-col>
        <el-col :span="24">
          <el-form-item prop="planList">
            <el-table
              size="medium"
              :data="form.planList"
              stripe
              border
              height="300"
            >
              <el-table-column
                label="序号"
                type="index"
                align="center"
                width="100"
              ></el-table-column>
              <el-table-column
                prop="subjectName"
                label="训练课目"
                show-overflow-tooltip
              >
                <template v-slot="{row, $index}">
                  <span v-if="row.type == 1">{{ row.subjectName }}</span>
                  <el-form-item
                    v-else
                    :prop="`planList.${$index}.subjectName`"
                    :rules="[
                      {
                        required: true,
                        message: '请选择训练课目',
                        trigger: 'blur'
                      }
                    ]"
                  >
                    <el-input
                      :disabled="type == '详情' ? true : false"
                      style="width: 100%;"
                      placeholder="请输入训练课目"
                      v-model="row.subjectName"
                      clearable
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="hour" label="训练单位" width="400">
                <template v-slot="{row, $index}">
                  <el-form-item
                    :prop="`planList.${$index}.orgId`"
                    :rules="[
                      {
                        required: true,
                        message: '请选择训练单位',
                        trigger: 'change'
                      }
                    ]"
                  >
                    <el-cascader
                      :disabled="type == '详情' ? true : false"
                      :ref="'selectTree' + row.id"
                      @change="changecase(row, 'selectTree' + row.id)"
                      style="width: 100%;"
                      placeholder="请选择训练单位"
                      v-model="row.orgId"
                      :options="orgList"
                      :props="{
                        emitPath: false,
                        label: 'name',
                        value: 'id',
                        multiple: true,
                        checkStrictly: true
                      }"
                      :key="row.id"
                      filterable
                      :show-all-levels="false"
                    ></el-cascader>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="startEndTime"
                label="训练起始日期"
                width="260"
              >
                <template v-slot="{row, $index}">
                  <el-form-item
                    :prop="`planList.${$index}.startEndTime`"
                    :rules="[
                      {
                        required: true,
                        message: '请训练起始日期',
                        trigger: 'change'
                      }
                    ]"
                  >
                    <el-date-picker
                      :disabled="type == '详情' ? true : false"
                      style="width: 100%;"
                      v-model="row.startEndTime"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="hour" label="训练时长" width="180">
                <template v-slot="{row, $index}">
                  <el-form-item
                    :prop="`planList.${$index}.hour`"
                    :rules="[
                      {
                        required: true,
                        message: '请选择训练单位',
                        trigger: 'change'
                      }
                    ]"
                  >
                    <el-input-number
                      :disabled="type == '详情' ? true : false"
                      controls-position="right"
                      :min="0"
                      :precision="2"
                      v-model="row.hour"
                    ></el-input-number>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                v-if="type == '详情' ? false : true"
                align="center"
                prop="fullname"
                label="操作"
                width="80"
              >
                <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-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" v-if="isActive == 1" @click="lastStep"
        >上一步</el-button
      >
      <el-button type="primary" v-if="isActive === 0" @click="nextStep"
        >下一步</el-button
      >
      <el-button
        v-if="isActive == 1 && type !== '详情'"
        :loading="saveLoading"
        type="primary"
        @click="handleSave"
      >
        确 认
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </span>

    <coursePlan ref="coursePlan" @getUser="getMaterials" />
  </el-dialog>
</template>

<script>
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import * as api from '@/api/examDataMenu/examManagerData/examPlanAll.js'
import moment from 'moment'
import coursePlan from '@/components/examDialog/coursePlan.vue'
import {treeDataByDem} from '@/api/systemInterface'

export default {
  name: 'AddEditDialog',
  components: {
    coursePlan
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    rowInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      rules: {
        year: [{required: true, message: '请选择年度', trigger: 'change'}],
        startEndTime: [
          {required: true, message: '请选择起始时间', trigger: 'change'}
        ],
        planList: [{required: true, message: '请选择课目', trigger: 'change'}]
      },
      form: {
        year: moment().format('YYYY'),
        planList: []
      },

      saveLoading: false,
      isActive: 0,

      orgList: []
      //课目字典
    }
  },
  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,

    changecase(row, ref) {
      this.$set(
        row,
        'orgName',
        this.$refs[ref].getCheckedNodes().map(item => {
          return {orgName: item.label, orgId: item.value}
        })
      )
    },
    async getTreeList() {
      this.orgList = await treeDataByDem()
    },
    delIndex(row) {
      this.form.planList = this.form.planList.filter(item => {
        return item.subjectId !== row.subjectId
      })
    },

    getMaterials(data) {
      this.$set(
        this.form,
        'planList',
        data.map(item => {
          return {
            subjectId: item.id,
            subjectName: item.name,
            hour: 0,
            startEndTime: this.form.startEndTime,
            orgId: [],
            type: 1,
            ...item
          }
        })
      )
    },

    increasePlan() {
      this.$refs.coursePlan.add(this.form.planList)
    },
    increaseOtherPlan() {
      let id = new Date().getTime()

      this.form.planList.push({
        subjectName: '',
        hour: 0,
        orgId: [],
        id,
        type: 2,
        startEndTime: this.form.startEndTime
      })
    },
    // 上一页
    lastStep() {
      this.isActive -= 1
    },
    // 下一页
    nextStep() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isActive += 1
        } else {
          this.$notify({
            type: 'warning',
            message: '请填写完整训练信息',
            duration: 2000
          })
        }
      })
    },

    // 打开弹层
    open() {
      this.getTreeList()
      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 {planList, startTime, endTime, ...form} = await api.tableDetail(id)
        let startEndTime = startTime && endTime ? [startTime, endTime] : []

        planList = planList.map(item => {
          item.orgId = item.orgId.split(',')
          item.orgName = item.orgName.split(',').map((val, i) => {
            return {
              orgName: val,
              orgId: item.orgId[i]
            }
          })
          item.name = item.subjectName
          item.startEndTime = [item.startTime, item.endTime]

          return item
        })

        this.form = {...form, startEndTime}
        this.$set(this.form, 'planList', planList)
      } 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.startTime = params.startEndTime[0]
          params.endTime = params.startEndTime[1]
          params.planList = params.planList.map(item => {
            item.orgName = item.orgName
              .filter(value => {
                return item.orgId.indexOf(value.orgId) > -1
              })
              .map(val => val.orgName)
              .join(',')
            item.orgId = item.orgId.join(',')
            item.startTime = item.startEndTime[0]
            item.endTime = item.startEndTime[1]
            delete item.id
            return item
          })

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

            if (state) {
              this.$emit('submit', this.id ? 'edit' : 'add')
              message = this.id ? '编辑' : '新增'
              this.$message.success(`补训训练计划${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>
=
