<template>
  <div class="page-contain new-work">
    <top-nav :title="title"
             :showQuery="false"
             :backFunc="returnLast"></top-nav>
    <van-form label-width="65px" class="form-class">
      <van-field readonly
                 clickable
                 required
                 label="报告类型"
                 :value="form.workTypeKey"
                 placeholder="请选择报告类型"
                 @click="showPicker = true"
                 input-align="right" />
      <van-popup v-model="showPicker"
                 round
                 position="bottom">
        <van-picker show-toolbar
                    :columns="workTypeKeys"
                    @cancel="showPicker = false"
                    @confirm="workTypeConfirm" />
      </van-popup>
      <date-select ref='dateSelRef'
                   :init-dateParam="form.dateParam"
                   :date-type="form.workType"
                   @close="closeDateSel" />
      <div class="row-wrap">
        <div>
          <label>知会人员</label>
        </div>
        <aws-org ref="awsOrgRef"
                 :init-active-ids="activeIds"
                 :init-users-select="usersSelect"
                 :only-one="false"
                 :module="{moduleId:3103,type:'1',typeName:'工作报告知会人员'}"
                 @orgClose="getOrgUser"></aws-org>
      </div>
      <div class="input-wrap">
        <div class="row">
          <div>
            <label>拜访报告</label>
          </div>
        </div>
        <van-row style="padding:8px">
          <van-col span="23"
                   style="border:1px solid #e9e9e9;padding:15px 0px;display: flex;flex-direction: column;justify-content: center;">
            <span style="padding:0px 15px;color:#008cee;display: flex;justify-content: space-between;"
                  v-for="(item,i) in visitList"
                  :key='i'><span @click="handleJump(item)" >{{item.visitCode}}</span>
              <van-icon name="cross"
                        @click="closeVisti(item)" />
            </span>
          </van-col>
          <van-col span="1"
                   class="fc8CEE"
                   style="display:flex;flex-direction:row;align-items:center;text-align:center;padding-left:8px">
            <van-icon name="add-o"
                      @click="showMyVisit"
                      class="add-icon" />
          </van-col>
        </van-row>
      </div>
      <div class="input-wrap">
        <div class="row">
          <div>
            <label>工作总结<span class="req-start">*</span> </label>
          </div>
        </div>
        <van-row v-for="(item, i) in workSumList"
                 :key="i">
          <van-col span="23">
            <van-field v-model="item.content"
                       autosize
                       class="textarea"
                       type="textarea"
                       :placeholder="i + 1 + '. 请输入'"
                       maxlength="300"
                       show-word-limit />
          </van-col>
          <van-col @click="changeRow('workSumList', i)"
                   span="1"
                   class="fc8CEE"
                   style="display:flex;flex-direction:row;min-height:30px;align-items:center;">
            <van-icon :name="i===0?'add-o':'close'"
                      class="add-icon" />
          </van-col>
        </van-row>
      </div>

      <div class="input-wrap">
        <div class="row">
          <div>
            <label>工作计划<span class="req-start">*</span> </label>
          </div>
        </div>
        <van-row v-for="(item, i) in workPlanList"
                 :key="i">
          <van-col span="23">
            <van-field v-model="item.content"
                       autosize
                       class="textarea"
                       type="textarea"
                       :placeholder="i + 1 + '. 请输入'"
                       maxlength="300"
                       show-word-limit />
          </van-col>
          <van-col @click="changeRow('workPlanList', i)"
                   span="1"
                   class="fc8CEE"
                   style="display:flex;flex-direction:row;min-height:30px;align-items:center;">
            <van-icon :name="i===0?'add-o':'close'"
                      class="add-icon" />
          </van-col>
        </van-row>
      </div>
      <van-popup v-model="showVisitPicker"
                 get-container="#app"
                 position="bottom">
        <connect-report-more ref="visitRef"
                             @close="closeConnectReport"
                             :createrId="byUid"
                             :init-ids="initReportId" />
      </van-popup>
      <!-- 相关任务 -->
      <related-task v-if="taskShow"
                    ref="taskRef"
                    :moduleId="3103"
                    :oper="oper"
                    :resultTaskList="taskInfoList"></related-task>

      <!-- 附件 -->
      <ls-file ref="fileRef"
               :attach-file-info-list="attachFileInfoList"></ls-file>
      <div class="footer-btn"
           :style="{paddingBottom:system==='ios'?'15px':'0px',background:'#fff'}">
        <van-button style="margin: 0px 1px"
                    v-for="(item, i) in btns"
                    :key="i"
                    :type="item.type"
                    :disabled="item.disabled"
                    @click="submit( item.param, item.autoSave)">{{ item.name }}</van-button>
      </div>
    </van-form>
    <van-overlay :show="showLoading">
      <div class="wrapper">
        <van-loading type="spinner"
                     size="60px" />
      </div>
    </van-overlay>
  </div>
</template>

<script>
import newtask from '../task/new-task.vue'
import dateSelect from './components/date-select.vue'
import clearkeepAlive from '../../common/clearkeepAlive'
import connectReportMore from '../../components/connect-report-more.vue'
import util from '../../common/util'
export default {
  components: { newtask, dateSelect, connectReportMore },
  props: { editData: Object },
  mixins: [clearkeepAlive],
  data () {
    return {
      byUid: 'byUid',
      system: util.appSystem(),
      showLoading: false,
      showVisitPicker: false,
      title: '新增工作报告',
      taskShow: false,
      oper: 'edit', // 是否编辑任务
      btns: [
        {autoSave: false, type: 'info', disabled: false, name: '提交', param: 'unread', backupName: '提交' },
        {autoSave: false, type: 'default', disabled: false, name: '保存', param: 'draft', backupName: '保存' }
      ],
      showNewTask: false,
      showReport: false,
      iscollapse: true,
      form: {
        // 报告类型
        workTypeKey: '',
        workType: '',
        // 报告日期
        dateParam: '',
        isAuto: true, //自动保存
      },
      // 编辑的时候，查询回来的详细数据,null时为新增
      detailInfo: null,
      initReportId: [], // 关联拜访报告初始化ID
      // 报告类型
      workTypes: [],
      workTypeKeys: [],
      showPicker: false,

      // 工作总结
      workSumList: [{ content: '' }],
      // 工作计划
      workPlanList: [{ content: '' }],
      // 任务列表
      taskInfoList: [],
      // 初始化用户选择的部门ID
      activeIds: [],
      // 初始化用户选择的用户列表
      usersSelect: [],
      // 初始化任务数据
      initTaskData: null,
      projectId: null,
      // 上传附件
      attachFileInfoList: [],
      visitList: [],
      params: null,
      startStatus: true, // 初始状态
      timeId: -1, //定时器id
      workId: '', //存储自动保存时的id
    }
  },
  watch: {
    'form.dateParam': {
      handler: function (val) {
        if (!this.startStatus) {
          this.getCurVisit(val, val)
        }
      }
    },
    deep: true
  },
  created () {
    this.getworkType()
    this.projectId = this.$route.query.projectId
      ? this.$route.query.projectId
      : '' // 从项目编辑，新增进展进来时
  },
  mounted () {
    this.$nextTick(() => {
      this.form.workType = 'daily'
      this.form.workTypeKey = '日报'
      if (this.params === null) {
        // 新增，取默认值
        this.$refs.awsOrgRef.getDefaultUser()
      }
      if (this.editData && this.editData !== null) {
        // 通过父子组件形式进来
        this.initData(this.editData)
        this.params = this.editData
      } else if (this.$route.params.id) {
        // 通过路由跳转进来
        this.params = this.$route.params
        this.initData(this.$route.params)
      } else {
        this.taskShow = true
        this.startStatus = false
      }
    })
    this.autoSaveForm();
  },
  beforeDestroy(){
    clearInterval(this.timeId); //销毁定时器
  },
  methods: {
    showMyVisit () {
      this.byUid = 'byUid'
      this.showVisitPicker = true
    },
    // 初始化数据
    initData (editData) {
      this.title = '编辑工作报告'
      this.getWorkDetail(editData)
    },
    // 拜访报告
    closeConnectReport (selReprotList) {
      if (selReprotList.length !== 0) {
        selReprotList.forEach(v => {
          let find = this.visitList.find(z => z.visitCode === v.visitCode)
          if (!find) {
            this.visitList.push(v)
          }
        })
      }
      this.showVisitPicker = false
    },
    // 拜访报告详情或编辑,草稿:编辑,非草稿:详情
    handleJump (row) {
      let url = 'visitDetail'
      // if (row.reviewStatus && row.reviewStatus === 'draft') {
      //   url = 'newVisit'
      // }
      this.$router.push({
        path: url,
        query: {
          rowId: row.id,
          from: 'newWork'
        }
      })
    },
    // 删除拜访报告
    closeVisti (row) {
      this.visitList = this.visitList.filter(v => v.visitCode !== row.visitCode)
    },
    // 查询当前拜访报告
    getCurVisit (startDate, endDate) {
      this.$axios.post({
        domain: 'crmUrl',
        url: 'visit.visitReportListByStatus',
        requestType: 'body',
        data: {
          'currPage': 1,
          'pageSize': 100,
          'queryParam': {
            'createEndTime': startDate,
            'createStartTime': endDate,
            'unDraftFlag': 'draft',
            'createrId': 'byUid'
            // 'ext5': 'default'
          }
        },
        success: function (res) {
          if (res.success) {
            let data = res.data.records || []
            this.visitList = data
          } else {
            this.$toast.fail(res.msg)
            this.finished = true
          }
        }.bind(this),
        error: function (res) {
          this.$toast.fail(res.msg)
          this.finished = true
        }.bind(this)
      })
    },
    // 查询工作报告详情
    getWorkDetail (editData) {
      let param = {
        id: editData.id,
        projectId: this.projectId ? this.projectId : ''
      }
      this.$axios.post({
        domain: 'crmUrl',
        url: 'work.getWorkDetail',
        requestType: 'body',
        data: param,
        success: (res) => {
          if (res.success) {
            let data = res.data
            this.detailInfo = data
            for (let key in data) {
              if (this[key]) {
                this[key] = data[key]
              }
            }
            for (let key in this.form) {
              if (data[key]) {
                this.form[key] = data[key]
              }
            }
            if (this.form['dateParam'] !== '') {
              this.$refs.dateSelRef.setTime(this.form['dateParam'])
            }
            // 知会人员
            if (data.informerList.length !== 0) {
              let usersSelect = []
              data.informerList.forEach(v => {
                v.name = v.userName
                v.uid = v.userId
                usersSelect.push(v)
              })
              this.usersSelect = usersSelect
              this.$refs.awsOrgRef.refreshUser(usersSelect)
            }
            // 拜访报告
            let citeVisitCodes = data.citeVisitCodes || []
            let visitLists = []
            if (citeVisitCodes.length !== 0) {
              citeVisitCodes.forEach(v => {
                visitLists.push({ id: v.value, visitCode: v.key })
              })
            }
            this.visitList = visitLists
            // 上传附件
            if (data.attachFileInfoList.length !== 0) {
              this.$refs.fileRef.refreshData(data.attachFileInfoList)
            }
          } else {
            this.$toast.fail(res.msg)
          }
          this.taskShow = true
          setTimeout(() => {
            this.startStatus = false
          }, 2000)
        }
      })
    },
    closeDateSel (value) {
      this.form.dateParam = value
    },
    closeVisitList () { },
    // 关闭部门用户选择
    getOrgUser (userData, index, status) {
      if (status) {
        this.usersSelect = userData
      }
    },
    // 返回上一页
    returnLast (data) {
      let path = this.$route.path
      if (path === '/newWork') {
        this.$router.back(-1)
      } else {
        this.$emit('workData', data)
      }
      this.clearCache()
    },
    // 相关任务展开与收起
    collapse () {
      this.iscollapse = !this.iscollapse
    },
    // 操作工作总结或工作计划
    changeRow (type, index) {
      if (index === 0) {
        this[type].push({
          content: ''
        })
      } else {
        let newArray = this[type].filter((v, i) => i !== index)
        this[type] = newArray
      }
    },
    // 查询报告类型
    getworkType () {
      this.$axios.get({
        domain: 'dictUrl',
        url: 'dict.datalist',
        data: {
          busSystem: 'cloud-crm-project',
          dictSign: 'Crm_Report_Type'
        },
        success: function (res) {
          if (res.success) {
            let data = res.data || []
            let workTypeKeys = []
            if (data.length !== 0) {
              data.forEach(v => {
                workTypeKeys.push(v.key)
              })
            }
            this.workTypes = data
            this.workTypeKeys = workTypeKeys
          } else {
            this.$toast.fail(res.msg)
          }
        }.bind(this),
        error: function (res) {
          this.$toast.fail(res.msg)
        }.bind(this)
      })
    },
    // 确认报告类型
    workTypeConfirm (value) {
      if (this.form.workTypeKey !== value) {
        this.form.dateParam = ''
      }
      this.form.workType = this.workTypes.find(v => v.key === value).vaule
      this.form.workTypeKey = value
      this.showPicker = false
    },
    // 展示形式的报告日期格式化成参数形式
    formatToParam (workType, date) {
      let dateString = date
      switch (workType) {
        case 'daily':
          dateString = date + ' 00:00:00' // 2021-01-01 to 2021-01-01 00:00:00
          break
        case 'week':
          dateString =
            date.split(',')[0] + '-' + date.split(',')[1].match(/第(\S*)周/)[1] // 2000,第1周（12.27-01.02） to 2020-01
          break
        case 'month':
          dateString = date
          break
        case 'season':
          dateString =
            date.split(',')[0] +
            '-' +
            this.seasonToDate(date.split(',')[1].match(/第(\S*)季度/)[1]) // "2001,第1季度" to 2001-01-01 00:00:00
          break
        case 'year':
          dateString = date
          break
      }
      return dateString
    },
    // 季度格式化传给后台格式
    seasonToDate (season) {
      let dateString = ''
      switch (season) {
        case '1':
          dateString = '01-01 00:00:00'
          break
        case '2':
          dateString = '04-01 00:00:00'
          break
        case '3':
          dateString = '07-01 00:00:00'
          break
        case '4':
          dateString = '10-01 00:00:00'
          break
      }
      return dateString
    },
    // 保存或提交
    submit (reviewStatus, autoSave) {
      if (!autoSave && this.form.workType === '') {
        this.$toast('报告类型不能为空！')
        return
      } else if (!autoSave && this.form.dateParam === '') {
        this.$toast('报告日期不能为空！')
        return
      } else if (
        !autoSave &&
        this.workSumList.length === 1 &&
        this.workSumList[0].content === ''
      ) {
        this.$toast('请填写工作总结！')
        return
      } else if (
        !autoSave &&
        this.workPlanList.length === 1 &&
        this.workPlanList[0].content === ''
      ) {
        this.$toast('请填写工作计划！')
        return
      }
      // 上传的文件列表
      let attachFileInfoList = []
      let fileList = this.$refs.fileRef.getDataList()
      if (fileList && fileList.length !== 0) {
        fileList.forEach(v => {
          attachFileInfoList.push({
            fileId: v.fileId,
            fileName: v.fileName,
            fileSize: v.fileSize
          })
        })
      }

      // 知会人员列表
      let informerParamList = []
      let userSelect = this.usersSelect
      if (userSelect.length !== 0) {
        userSelect.forEach(v => {
          informerParamList.push({
            email: v.email,
            informerType: 1,
            userId: v.uid,
            userName: v.name
          })
        })
      }
      // 关联的拜访报告
      let citeVisitCodes = []
      let visitList = this.visitList
      if (visitList.length !== 0) {
        visitList.forEach(v => {
          citeVisitCodes.push({
            key: v.visitCode,
            value: v.id
          })
        })
      }
      this.workPlanList.map((v, i) => {
        v.id = ''
        v.contentSort = i + 1
      })
      this.workSumList.map((v, i) => {
        v.id = ''
        v.contentSort = i + 1
      })
      let param = {
        attachFileInfoList: attachFileInfoList, // 上传的文件列表
        informerParamList: informerParamList, // 知会人员列表
        taskParamList: this.$refs.taskRef.taskInfoList, // 任务列表
        citeVisitCodes: citeVisitCodes,
        workPlanList: this.workPlanList, // 工作计划列表
        workSumList: this.workSumList, // 工作总结列表
        workType: this.form.workType, // 报告类型
        dateParam: this.formatToParam(
          this.form.workType,
          this.$refs.dateSelRef.dateParam
          // this.form.dateParam
        ), // 报告日期
        reportBigType: '', // 报告大类型：{projectReport:项目报告,workReport:工作报告}
        reviewStatus: reviewStatus // 批阅状态 保存还是提交
      }
      param.id = this.workId
      param.isAuto = autoSave;

      if (this.projectId) {
        param.projectId = this.projectId
        // param.theme = this.$refs.myForm.param.theme;
        param.reportBigType = 'projectReport'
      } else {
        param.reportBigType = 'workReport'
      }
      if (this.detailInfo !== null) { // 添加接口返回的详细信息
        for (let key in this.detailInfo) {
          if (!param[key]) {
            param[key] = this.detailInfo[key]
          }
        }
      }
      autoSave?this.showLoading = false : this.showLoading = true
      if(!autoSave){
         this.btns.map(v => {
           v.disabled = true
           v.name = v.param === reviewStatus ? '请稍后...' : v.name
         })
      }

      this.$axios.post({
        domain: 'crmUrl',
        url: 'work.saveOrUpdateWorkReport',
        requestType: 'body',
        isShow: false,
        data: param,
        success: function (res) {debugger
          this.showLoading = false
          if (res.success) {
            this.workId = res.data.id
            if(!autoSave){
              this.$toast.success(reviewStatus === 'draft' ? '保存' : '提交' + '保存成功！')
              this.returnLast(param)
            }
          } else {
            if(!autoSave){
              this.$toast.fail(res.msg)
            }
          }
          this.btns.map(v => {
            v.disabled = false
            v.name = v.backupName
          })
        }.bind(this)
      })
    },
    //自动保存
    autoSaveForm(){
      let _this = this, autoSave=true;
      clearInterval(this.timeId);
      this.timeId = setInterval(()=>{
        this.submit('draft', autoSave);
      }, 1000*30)

    },

  }
}
</script>

<style lang="scss">
.add-icon {
  color: #008cee;
}
.page-contain.new-work {
  padding: 82px 0px;
  background: #fff;
  
  .form-class{
    height: calc(100vh - 82px);
    overflow-y: auto;
    padding-bottom: 152px;
  }
  label {
    color: #646566;
  }
  .van-form {
    .row-wrap {
      padding: 10px 15px;
      border-bottom: 1px solid #ddd;
      label {
        color: #646566;
        margin-right: 15px;
      }
    }
    .input-wrap {
      border-bottom: 1px solid #ddd;
      padding-right: 20px;
      .van-cell {
        border-bottom: none;
      }
      .row {
        padding: 5px 15px;
        display: flex;
        justify-content: space-between;
        border: none;
      }
    }

    .new-task-btn {
      width: 90%;
      margin: 0 auto;
      > .van-button {
        height: 80px;
        background: #ecf5ff;
        border: 1px solid #b3d8ff;
        border-radius: 5px;
        color: #008cee;
        width: 100%;
      }
    }
    .report-btn {
      width: 90%;
      margin: 10px auto;
      display: flex;

      > .van-button {
        flex: 1;
        height: 80px;
        background: #eef8f3;
        border: 1px solid #a1d8bc;
        border-radius: 5px;
        color: #57b986;
      }
    }
  }
}
</style>
