<template>
  <div>
    <NavBar :go="{ type: 'push', path: '/training' }" />
    <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
        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
        name="datetimePicker"
        :value="form.trainingStartDateTime"
        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"
          @confirm="onConfirmDate"
          @cancel="showStartDate = false"
        />
      </van-popup>
      <!-- 培训结束时间 -->
      <van-field
        readonly
        clickable
        name="datetimePicker"
        :value="form.trainingEndDateTime"
        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"
          @confirm="onConfirmEndDate"
          @cancel="showEndDate = false"
        />
      </van-popup>
      <div class="mainItem">
      <div class="label labelPeople">培训资料</div>
      <template v-for="item in studyList">
        <div :key="item.url" class="imglIST" style="{width:'100px',height: '100px';}">

          <imgCom :width="'100'" v-if="item.url&&item.type==0"  :height="'100'" :src="item.url"></imgCom>
          <!-- <VuePdf v-else :src="item.url"></VuePdf> -->
          <VuePdf  v-else  :src="item.url"></VuePdf>
        </div>
      </template>
    </div>
      <!-- 培训内容 -->
      <van-field
        required
        :rules="[{ required: true, message: '培训内容不能为空' }]"
        v-model="form.content"
        name="content"
        label="培训内容"
        type="textarea"
        row="3"
        maxlength="2000"
        show-word-limit
        placeholder="请填写培训内容"
      />
      <!-- 总结 -->
      <van-field
        required
        :rules="[{ required: true, message: '总结不能为空' }]"
        v-model="form.note"
        name="note"
        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" label="上传图片">
        <template #input>
          <Upload v-model="form.imageList" :maxCount="5" @input="listHandler"></Upload>
        </template>
      </van-field>
      <div class="btns">
        <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 imgCom from '@/components/imgCom/index.vue'
import { gettrainingInfo, edittrainingInfo } from '@/api/training.js'
import { newDateTime } from '@/utils/date.js'
import { Dialog, Toast } from 'vant'
import VuePdf from "@/components/pdfCom/index.vue"

export default {
  name: 'SocAppAddTraining',
  components: {
    VuePdf,
    NavBar,
    imgCom,
    Upload,
    CheckPeople
  },
  data() {
    return {
      this_window:window,
      studyList: [], //学习资料数组
      startDateTime: new Date(),
      endDateTime: new Date(),
      falg: false, //校验是否通过
      username: '',
      password: '',
      form: {
        typeText: '', //培训类型
        type: '', //培训value
        content: '', //培训内容
        note: '', //培训总结
        taskUserList: [], //人员数组
        imageList: [], //图片数组
        trainingStartDateTime: '', //开始时间
        trainingEndDateTime: '' //结束时间
      },
      trainingData: {},
      userPeopleList: [], //参与人员数组
      lackPeopleList: [], //缺席人员数组
      showPicker: false, //培训类型显示隐藏
      showStartDate: false, //开始时间显示隐藏
      showEndDate: false, //结束时间显示隐藏
      columns: ['每月安全培训教育', '专项安全培训教育']
    }
  },
  created() {
    //获取详情信息
    gettrainingInfo(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)
           console.log(i);
            if(i.url.split('.')[1]=='pdf'){
              i.type=1
            }else{
              i.type=0
            }
            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: {
    // 查看pdf
    
    onSubmit(values) {
      console.log('submit', values)
      Dialog.confirm({
        title: '',
        message: '是否提交培训数据?'
      })
        .then(() => {
          // on confirm
        })
        .catch(() => {
          // on cancel
        })
    },
    //培训类型确认
    onConfirm(val) {
      this.form.typeText = val //培训类型赋值

      switch (val) {
        case '每月安全培训教育':
          this.form.type = '0'

          break
        case '专项安全培训教育':
          this.form.type = '1'
          break
      }
      this.showPicker = false
    },
    //开始时间确认
    onConfirmDate(val) {
      this.form.trainingStartDateTime = newDateTime(val)

      this.showStartDate = false
    },
    //结束时间
    onConfirmEndDate(val) {
      this.form.trainingEndDateTime = newDateTime(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) {
      console.log(list,'mmmm');
      this.form.imageList = list || []
    },
    //表单提交前校验
    beforSubmitV() {
      this.falg = false
      let startDate = JSON.parse(JSON.stringify(this.form.trainingStartDateTime))
      startDate = Date.parse(new Date(startDate))

      let endDate = JSON.parse(JSON.stringify(this.form.trainingEndDateTime))
      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.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)

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

        ...obj
      }).then(res => {
        let { code, msg } = res
        if (code == 200) {
          Toast('登记成功')
          this.$router.push('/training')
        } else {
          Toast(msg)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.mainItem {
  display: flex;
  font-size: 28px;
  padding: 34px;
  justify-content: space-between;
  background-color: #fff;
  div {
    flex: 1;
    text-align: left;
  }
  .label {
    width: 200px;
    flex: none;
    text-align: left;
  }
}
.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>
