<template>
  <div>
    <NavBar :go="{ type: 'push', path: '/rehearsalTask' }" />
    <van-form class="bigbox" ref="form">
      <div class="mainItem">
        <div class="label">标题</div>
        <div>{{ trainingData.title }}</div>
      </div>
      <div class="mainItem">
        <div class="label">单位名称</div>
        <div>{{ trainingData.orgName }}</div>
      </div>
      <!-- 演练时间 -->
      <van-field
        readonly
        clickable
        name="datetimePicker"
        :value="form.drillStartTime"
        required
        :rules="[{ required: true, message: '演练开始时间不能为空' }]"
        label="演练开始时间"
        placeholder="请选择演练开始时间"
        @click="showStartDate = true"
      />
      <van-popup v-model="showStartDate" position="bottom">
        <van-datetime-picker
          v-model="startDateTime"
          type="datetime"
          :formatter="formatter"
          confirm-button-text="确定"
          @confirm="onConfirmDate"
          @cancel="showStartDate = false"
        />
      </van-popup>
      <!-- 结束时间 -->
      <van-field
        readonly
        clickable
        name="datetimePicker"
        :value="form.drillEndTime"
        required
        :rules="[{ required: true, message: '演练结束时间不能为空' }]"
        label="演练结束时间"
        placeholder="请选择演练结束时间"
        @click="showEndDate = true"
      />
      <van-popup v-model="showEndDate" position="bottom">
        <van-datetime-picker
          v-model="endDateTime"
          type="datetime"
          :formatter="formatter"
          confirm-button-text="确定"
          @confirm="onConfirmEndDate"
          @cancel="showEndDate = false"
        />
      </van-popup>

      <!-- 演练地点 -->
      <van-field
        required
        :rules="[{ required: true, message: '演练地点不能为空' }]"
        v-model="form.drillSite"
        name="drillSite"
        label="演练地点"
        type="textarea"
        row="1"
        maxlength="50"
        show-word-limit
        placeholder="请填写演练地点"
      />
      <!-- 演练计划资料 -->
      <div class="mainItem mainItemData">
        <p class="label labelPeople">演练计划资料</p>
        <div>
          <div v-for="item in studyList" :key="item.name">
            <van-tag type="primary" @click="tagHandler(item)" class="tagCls" plain>{{ item.name }}</van-tag>
          </div>
        </div>
      </div>
      <!-- //演练项目 -->
      <van-field
        readonly
        clickable
        required
        name="picker"
        :value="form.typeText"
        label="演练项目"
        :rules="[{ required: true, message: '演练项目不能为空' }]"
        placeholder="请选择演练项目"
        @click="showPicker = true"
      />

      <van-popup v-model="showPicker" position="bottom">
        <van-picker show-toolbar :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
      </van-popup>
      <!-- 演练类型 -->
      <!-- <van-field
        readonly
        clickable
        required
        name="picker"
        :value="form.categoryText"
        label="演练类型"
        :rules="[{ required: true, message: '演练类型不能为空' }]"
        placeholder="请选择演练类型"
        @click="showPickerType = true"
      /> -->
      <van-popup v-model="showPickerType" position="bottom">
        <van-picker show-toolbar :columns="columnsType" @confirm="onConfirmType" @cancel="showPickerType = false" />
      </van-popup>
      <!-- 参考预案演练库 -->
      <div class="mainItem">
        <div class="label labelPeople">
          <van-button size="small" @click="rehearsalHandler" type="info">参考演练范本库</van-button>
        </div>
      </div>
      <!-- 演练库选择组件 -->
      <yldialog ref="yldialog" :dictValue="form.type" @checkList="checkList"></yldialog>
      <!-- 预设案由 -->

      <van-field
        required
        :rules="[{ required: true, message: '预设案由不能为空' }]"
        v-model="form.presetCase"
        name="presetCase"
        label="预设案由"
        type="textarea"
        row="3"
        maxlength="2000"
        show-word-limit
        placeholder="请填写预设案由"
      />

      <!-- 演练情况 -->
      <van-field
        required
        :rules="[{ required: true, message: '演练情况不能为空' }]"
        v-model="form.drillSituation"
        name="drillSituation"
        label="演练情况"
        type="textarea"
        row="3"
        maxlength="2000"
        show-word-limit
        placeholder="请填写演练情况"
      />
      <van-field
        required
        :rules="[{ required: true, message: '点评总结不能为空' }]"
        v-model="form.comment"
        name="comment"
        label="点评总结"
        type="textarea"
        row="3"
        maxlength="2000"
        show-word-limit
        placeholder="请填写点评总结"
      />
      <!-- 参与人员 -->

      <!-- 必填 -->
      <CheckPeople
        ref="checkPeople"
        :userList="userPeopleList"
        :organizationId="trainingData.orgId"
        :isRequired="true"
        @userList="userListHandler"
      ></CheckPeople>
      <!-- 缺席人员 -->
      <CheckPeople
        ref="checkPeople"
        :userList="lackPeopleList"
        :inpitLabel="'缺席人员'"
        :organizationId="trainingData.orgId"
        :isRequired="false"
        @userList="lackUserListHandler"
      ></CheckPeople>
      <!-- 上传 -->
      <van-field readonly clickable name="uploader" required label="上传图片">
        <template #input>
          <Upload v-model="form.imageList" :multiple="true" :maxCount="10" @input="listHandler"></Upload>
        </template>
      </van-field>
      <div class="btns" v-show="isBtn">
        <van-button type="info" @click="submitHandler(1)">保存</van-button>
        <van-button type="info" @click="submitHandler(2)">提交</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import NavBar from '@/components/NavBar'
import CheckPeople from '@/components/peopleList/index.vue'
import Upload from '@/components/upload/index.vue'
import { onresizeHandler } from '@/utils/onresizeMixins.js'
import { getrehearsalInfo, drillInfo } from '@/api/drillTask.js'
import { newDateTimeMin } from '@/utils/date.js'
import { Dialog, Toast } from 'vant'
import yldialog from './dialog.vue'
import VuePdf from '@/components/pdfCom/index.vue'

export default {
  name: 'SocAppAddTraining',
  mixins: [onresizeHandler],
  components: {
    VuePdf,
    yldialog,
    NavBar,

    Upload,
    CheckPeople
  },
  data() {
    return {
      // this_window: window,
      studyList: [], //资料数组
      startDateTime: new Date(),
      endDateTime: new Date(),

      falg: false, //校验是否通过

      form: {
        typeText: '', //演练项目类型
        type: '', //演练value
        category: '', //演练类型value
        categoryText: '', //演练类型text
        drillSite: '', //演练地点
        note: '', //演练总结
        taskUserList: [], //人员数组
        imageList: [], //图片数组
        comment: '',
        presetCase: '', //预设案由
        drillSituation: '', //演练情况
        drillEndTime: '', //结束时间
        drillStartTime: '' //开始时间
      },
      trainingData: {},
      userPeopleList: [], //参与人员数组
      lackPeopleList: [], //缺席人员数组
      showPicker: false, //演练类型显示隐藏
      showPickerType: false, //演练类型显示隐藏
      showStartDate: false, //开始时间显示隐藏
      showEndDate: false, //结束时间显示隐藏
      columns: [],
      columnsType: [],
      columnsList: [],
      columnsListType: []
    }
  },
  created() {
    //获取数据字典
    this.getDictHandler('core_drill_type', res => {
      this.columnsList = res
      this.columns = res.map(item => item.dictLabel)
    })
    this.getDictHandler('core_drill_category', res => {
      this.columnsListType = res
      this.columnsType = res.map(item => item.dictLabel)
    })
    //获取详情信息
    getrehearsalInfo(this.$route.params.id).then(res => {
      let { code, data, msg } = res
      if (code == 200) {
        this.trainingData = data
        if (!data.taskUserList) {
          data.taskUserList = []
        }
        let newlist = data.fileList || []
        if (newlist.length > 0) {
          newlist.forEach(item => {
            let i = JSON.parse(item)

            if (i.url.split('.')[1] == 'pdf') {
              i.type = 1
            } else {
              i.type = 0
            }
            i.path = i.url
            this.studyList.push(i)
          })
        }
        if (!data.imageList) {
          data.imageList = []
        } else {
          let list = []
          data.imageList = data.imageList.split(',')

          data.imageList.forEach(item => {
            list.push({
              name: '',
              path: item
            })
          })
          data.imageList = list || []
        }
        Object.assign(this.form, data)
        // checkPeople

        this.form.taskUserList
          .map(item => {
            if (item.type === 1) {
              this.userPeopleList.push(item)
              return item.userName
            }
          })
          .join(',')

        this.form.taskUserList
          .map(item => {
            if (item.type === 2) {
              this.lackPeopleList.push(item)
              return item.userName
            }
          })
          .join(',')
      }
    })
  },
  mounted() {},

  methods: {
    //日期选择组件formatter
    formatter(type, val) {
      if (type === 'month') {
        return `${val}月`
      } else if (type === 'day') {
        return `${val}日`
      } else if (type === 'year') {
        return `${val}年`
      } else if (type === 'hour') {
        return `${val}时`
      } else if (type === 'minute') {
        return `${val}分`
      }
      return val
    },
    //预案演练选中数据
    checkList(list) {
      this.form.presetCase = list[0].defaultCause
    },
    //打开演练库弹框
    rehearsalHandler() {
      this.$refs.yldialog.init()
    },

    //演练项目确认
    onConfirm(val) {
      this.form.typeText = val //演练项目赋值
      this.columnsList.forEach(item => {
        if (val == item.dictLabel) {
          this.form.type = item.dictValue
        }
      })

      this.showPicker = false
    },
    //演练类型确认
    onConfirmType(val) {
      this.form.categoryText = val //演练类型赋值
      this.columnsListType.forEach(item => {
        if (val == item.dictLabel) {
          this.form.category = item.dictValue
        }
      })

      this.showPickerType = false
    },
    //演练时间确认
    onConfirmDate(val) {
      this.form.drillStartTime = newDateTimeMin(val)

      this.showStartDate = false
    },
    //结束时间
    onConfirmEndDate(val) {
      this.form.drillEndTime = newDateTimeMin(val)
      this.showEndDate = false
    },
    userListHandler(list) {
      list.forEach(item => {
        ;(item.type = 1), (item.userId = item.id)
        item.userName = item.username
        item.name = item.userName
        delete item.username
      })

      this.userPeopleList = list
    },
    lackUserListHandler(list) {
      list.forEach(item => {
        item.type = 2
        ;(item.userId = item.id), (item.userName = item.username)
        delete item.username
      })

      this.lackPeopleList = list
    },
    //上传附件成功
    listHandler(list) {
      this.form.imageList = list || []
    },
    //表单提交前校验
    beforSubmitV() {
      this.falg = false
      let startDate = JSON.parse(JSON.stringify(this.form.drillStartTime))
      startDate = Date.parse(new Date(startDate))

      let endDate = JSON.parse(JSON.stringify(this.form.drillEndTime))
      endDate = Date.parse(new Date(endDate))
      if (startDate > endDate) {
        Toast('演练开始时间不能大于演练结束时间')
        this.falg = true
        return
      }

      if (this.form.imageList.length == 0) {
        Toast('上传图片不能为空')
        this.falg = true
        return
      }
      if (this.userPeopleList.length == 0) {
        Toast('参与人员不能为空!')
        this.falg = true
        return
      }

      if (this.userPeopleList.length > this.lackPeopleList.length) {
        let isTrue = false
        this.userPeopleList.forEach(item => {
          this.lackPeopleList.forEach(i => {
            if (item.userId == i.userId) {
              isTrue = true
            }
          })
        })
        if (isTrue) {
          Toast('参与人员与缺席人员存在同一个人请修正!')
          this.falg = true
        }
      } else {
        let isTrue = false
        this.lackPeopleList.forEach(item => {
          this.userPeopleList.forEach(i => {
            if (item.userId == i.userId) {
              isTrue = true
            }
          })
        })
        if (isTrue) {
          Toast('参与人员与缺席人员存在同一个人请修正!')
          this.falg = true
        }
      }
    },
    //表单提交校验
    submitHandler(type) {
      Dialog.confirm({
        title: '',
        message: `是否${type === 2 ? '提交' : '保存'}演练数据?`
      })
        .then(() => {
          if (type === 1) {
            //type 1保存2提交
            // this.beforSubmitV()
            this.submitHandlerConfirm(type)
          } else {
            this.beforSubmitV() //校验
            if (!this.falg) {
              //校验通过触发
              this.$refs.form.validate().then(() => {
                this.submitHandlerConfirm(type)
              })
            }
          }
        })
        .catch(() => {
          // on cancel
        })
    },
    // 表单提交
    submitHandlerConfirm(type) {
      let obj = JSON.parse(JSON.stringify(this.form))

      obj.imageList = obj.imageList.map(item => item.path).join(',')
      console.log(obj.imageList)
      obj.taskUserList = []

      obj.taskUserList.push(...this.userPeopleList, ...this.lackPeopleList)

      obj.drillStartTime = obj.drillStartTime ? obj.drillStartTime + ':00' : ''

      obj.drillEndTime = obj.drillEndTime ? obj.drillEndTime + ':00' : ''

      drillInfo({
        id: this.trainingData.id,
        submitType: type,

        ...obj
      }).then(res => {
        let { code, msg } = res
        if (code == 200) {
          Toast(`${type == 1 ? '保存' : '提交'}成功`)
          this.$router.push('/rehearsalTask')
        } else {
          Toast(msg)
        }
      })
    },
    tagHandler(i) {
      let str = i.name.split('.')[1]
      if (str == 'png' || str == 'jpg' || str == 'jpeg' || str == 'pdf') {
        //当前是图片||PDF
        this.openFilePreview(i)
      } else {
        const filePath = `${process.env.NODE_ENV === 'development' ? '/dev' : window.origin}${i.url}`
        const tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = filePath
        tempLink.setAttribute('download', i.name)
        tempLink.setAttribute('target', '_blank')
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.mainItem {
  display: flex;
  font-size: 28px;
  align-items: center;
  padding: 34px;
  justify-content: space-between;
  background-color: #fff;
  flex-wrap: wrap;
  div {
    flex: 1;
    text-align: left;
  }
  p {
  }
  .label {
    width: 230px;
    flex: none;
  }
  .labelPeople {
    margin-bottom: 20px;
  }
}
.mainItemData {
  justify-content: end;
}
.tagCls {
  margin-bottom: 20px;
  margin-left: 10px;
}
.bigbox {
  height: calc(100vh - 200px);
  overflow: scroll;
}
// .imglIST{
//   width: 100px;
//   height: 100px;
// }
.btns {
  position: fixed;
  bottom: -7%;
  height: 200px;
  width: 100%;
  background-color: #fff;
  // margin: 16px;
  display: flex;

  justify-content: space-around;
  .van-button {
    width: 300px;
    margin-left: 50px;
  }
}
</style>
