<template>
  <div class="page-contain list-contain">
    <top-nav :title="title"
             :showQuery="false"
             :backFunc="returnLast"></top-nav>
    <div :style="{marginTop: paddingTop && marginT ? paddingTop + 'px' : '0'}">
      <van-form label-width="65px" class="form-class" >
        <van-field :disabled="disabled"
                   readonly
                   clickable
                   :value="paramForm.customerName"
                   label="关联客户"
                   placeholder="点击选择"
                   @click="addCustomer"
                   input-align="right" />
        <van-popup v-model="showCustomerPicker"
                   position="bottom"
                   :lock-scroll="false"
                   get-container="#app">
          <customer-list @close="closeCustomerList"
                         :init-id="initCustomerId" />
        </van-popup>
        <van-field readonly
                   clickable
                   required
                   :value="paramForm.itemTypeKey"
                   label="事项类型"
                   placeholder="点击选择"
                   @click="showItemPicker = true"
                   input-align="right" />
        <van-popup v-model="showItemPicker"
                   position="bottom">
          <van-picker show-toolbar
                      value-key="key"
                      :columns="itemTypes"
                      @confirm="onConItemfirm"
                      @cancel="showItemPicker = false" />
        </van-popup>

        <van-field readonly
                   clickable
                   required
                   :value="paramForm.taskSourceKey"
                   label="任务来源"
                   placeholder="点击选择"
                   @click="showSourcePicker = true"
                   input-align="right" />
        <van-popup v-model="showSourcePicker"
                   position="bottom">
          <van-picker show-toolbar
                      :columns="taskSources"
                      value-key="key"
                      @confirm="onSourceConfirm"
                      @cancel="showSourcePicker = false"
                      :disabled="isEdit" />
        </van-popup>

        <van-field readonly
                   clickable
                   required
                   :value="paramForm.emergencyDegreeKey"
                   label="紧要程度"
                   placeholder="点击选择"
                   @click="showemergencyPicker = true"
                   input-align="right" />
        <van-popup v-model="showemergencyPicker"
                   position="bottom">
          <van-picker show-toolbar
                      value-key="key"
                      :columns="emergencys"
                      @confirm="onEmergencyConfirm"
                      @cancel="showemergencyPicker = false" />
        </van-popup>

        <!-- <van-cell title="选择截止时间"
                :value="paramForm.taskRequestDateFormat"
                @click="showTimePicker = true" />
      <van-calendar v-model="showTimePicker"
                    @confirm="onTimeConfirm"
                    :min-date="minDate"
                    :max-date="maxDate"
                    color="#1989fa" /> -->
        <van-field readonly
                   clickable
                   required
                   label="截止时间"
                   :value="paramForm.taskRequestDateFormat"
                   placeholder="选择截止时间"
                   input-align="right"
                   @click="showTimePicker = true" />
        <van-popup v-model="showTimePicker"
                   round
                   position="bottom">
          <van-datetime-picker type="date"
                               title="截止时间"
                               v-model="currentDate"
                               :min-date="minDate"
                               :max-date="maxDate"
                               @confirm="onTimeConfirm"
                               @cancel="showTimePicker = false" />
        </van-popup>

        <van-field v-model="paramForm.taskContent"
                   rows="3"
                   autosize
                   required
                   label="任务描述"
                   type="textarea"
                   maxlength="300"
                   placeholder="请输入"
                   show-word-limit
                   class="textarea" />

        <div class="row">
          <div>
            <label>
              负责人员
              <span class="req-start">*</span>
            </label>
          </div>
          <aws-org ref="awsOrgRef"
                   :init-active-ids="activeTaskIds"
                   :init-users-select="usersSalesSelect"
                   :only-one="true"
                   @orgClose="taskUserInfo"></aws-org>
        </div>

        <div class="row">
          <div>
            <label>
              协同人员
              <span class="req-start"></span>
            </label>
          </div>
          <aws-org ref="awsInfoOrgRef"
                   :init-active-ids="activeIds"
                   :init-users-select="usersTaskSelect"
                   :only-one="false"
                   @orgClose="xietongClose"></aws-org>
        </div>
        <van-field readonly
                   clickable
                   :value="paramForm.projectCode"
                   label="关联项目"
                   placeholder="点击选择"
                   @click="projectVisitPickerClick('showProjectPicker')"
                   input-align="right" />
        <van-popup v-model="showProjectPicker"
                   get-container="#app"
                   position="bottom">
          <connect-project ref="projectRef"
                           @close="closeConnectProject"
                           :init-id="initProjectId"
                           :customerId="paramForm.customerId" />
        </van-popup>

        <van-field :disabled="disabled"
                   readonly
                   clickable
                   :value="paramForm.visitReportCode"
                   label="关联拜访"
                   placeholder="点击选择"
                   @click="projectVisitPickerClick('showVisitPicker')"
                   input-align="right"
                   :style="{ background: background }" />
        <van-popup v-model="showVisitPicker"
                   get-container="#app"
                   position="bottom">
          <connect-report ref="visitRef"
                          @close="closeConnectReport"
                          :init-id="initReportId"
                          :customerId="paramForm.customerId" />
        </van-popup>

        <!-- 审批操作 -->
        <ls-apploval ref="operReviewer"
                     @send="getChildParam"
                     v-show="handle"></ls-apploval>

        <div class="footer-btn"
             v-if="!onlyRead"
             :style="{paddingBottom:system==='ios'?'15px':'0px',background:'#fff'}">
          <!-- <van-button type="info"
                      v-if="!isCallBack"
                      native-type="submit"
                      @click="submitForm('dealing')">提交</van-button>
          <van-button :type="isCallBack?'info':'default'"
                      native-type="submit"
                      @click="submitForm('draft')">保存</van-button> -->
          <van-button style="margin: 0px 1px"
                      v-for="(item, i) in btns"
                      :key="i"
                      :type="item.type"
                      :disabled="item.disabled"
                      @click="submitForm(item.param, item.autoSave)">
            {{ item.name }}
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import commonSelectList from '@/common/commonSelectList.js'
import connectProject from '../../components/connect-project.vue'
import connectReport from '../../components/connect-report.vue'
import customerList from '../../components/customer-list.vue'
import util from '../../common/util'
import clearkeepAlive from '../../common/clearkeepAlive.js'
import approveReback from '../../common/approveReback'
export default {
  name: 'task-index',
  components: { connectProject, connectReport, customerList },
  props: { isCallBack: Boolean, moduleId: Number, taskData: Object, marginT: Boolean },
  mixins: [clearkeepAlive, approveReback],
  data () {
    return {
      disabled: false,
      background: '',
      button: false,
      handle: false,
      showAdd: true,
      system: util.appSystem(),
      onlyRead: false, // 是否只读
      title: '新增任务',
      initCustomerId: '', // 客户列表初始化ID
      initProjectId: '', // 关联项目初始化ID
      initReportId: '', // 关联拜访报告初始化ID
      activeIds: [], // 部门
      usersSalesSelect: [], // 用户
      btns: [{autoSave: false, type: this.isCallBack ? 'info' : 'default', disabled: false, name: '保存', param: 'draft', backupName: '保存' }],
      minDate: new Date(2000, 0, 1),
      maxDate: new Date(2040, 10, 1),
      currentDate: new Date(2021, 0, 17),
      activeTaskIds: [], // 部门
      usersTaskSelect: [], // 用户
      detailInfo: {
        status: '',
        busId: '',
        moduleId: 3104
      },
      operReviewer: {},
      paramForm: {
        userId: '',
        customerId: '',
        customerName: '',
        emergencyDegree: '',
        emergencyDegreeKey: '',
        notifyContent: '',
        notifyId: '',
        extId: '',
        informerParamList: [],
        modelId: this.modelId || 3104,
        notifyWayId: 'dingding',
        notifyWayName: '',
        modelType: '',
        parentTaskId: '',
        recordStatus: '',
        projectCode: '',
        relatedProjectsNumber: '',
        status: 'draft',
        statusKey: '草稿',
        taskContent: '',
        taskCompletedDate: '',
        itemType: '',
        itemTypeKey: '',
        taskId: '',
        taskLookOver: 0,
        taskRequestDate: '',
        taskRequestDateFormat: '',
        taskSource: '',
        taskSourceKey: '', // 任务来源key
        taskTitle: '',
        taskUser: '',
        taskUserId: '',
        visitReportCode: '',
        visitReportNumber: '',
        isAuto: true, //自动保存
      },
      value: '',
      value1: '',
      show: false,
      taskSources: [], // 任务来源
      customers: [], // 客户
      itemTypes: [], // 事项类型
      notifyWays: [], // 提醒类型
      emergencys: [], // 紧要程度
      projects: [], // 关联项目
      visits: [], // 关联拜访报告
      showCustomerPicker: false,
      showItemPicker: false,
      isEdit: true,
      showSourcePicker: false,
      showTimePicker: false,
      showNotifyPicker: false,
      showemergencyPicker: false,
      showProjectPicker: false,
      showVisitPicker: false,
      checked: '',
      isDisabled: false,
      lastAndLastRoute: ['/visitList', '/workList'], // 上两级路由
      lastRoute: ['/home', '/taskList', '/newWork', '/newVisit'],
      paddingTop: localStorage.getItem('paddingTop'),
      timeId: -1, //定时器id
    }
  },
  created () {
    if (this.taskData) {
      if ((this.taskData.status && this.taskData.status !== 'draft') || (this.taskData.ext1 && this.taskData.ext1 !== 'add')) {
        this.onlyRead = true
      }
    } else {
      this.getDetails()
    }
    this.defaultDate()
    this.getDict()
    this.defaultTaskSource()

    // if (this.modelId === 3102) {
    //   this.showVisitPicker = false
    // }
    if (!this.isCallBack) {
      this.btns.unshift({autoSave: false, type: 'info', disabled: false, name: '提交', param: 'dealing', backupName: '提交' })
    }
    this.autoSaveForm();
  },
  beforeDestroy(){
    clearInterval(this.timeId); //销毁定时器
  },
  methods: {
    addCustomer () {
      if (!this.disabled) {
        this.showCustomerPicker = true
      }
    },
    getChildParam (param) {
      // 控制提交按钮是否显示
      this.button = param.buttion
      this.handle = param.handle
      if (this.handle) {
        this.btns = [{ type: 'info', disabled: false, name: '提交', param: 'dealing', backupName: '提交' }]
      }
    },
    // 客户列表
    closeCustomerList (selCustomerObject) {
      if (selCustomerObject !== null) {
        if (this.paramForm.customerId !== selCustomerObject.customerNo) {
          this.paramForm.projectCode = ''
          this.paramForm.relatedProjectsNumber = ''
          this.paramForm.visitReportCode = ''
          this.paramForm.visitReportNumber = ''
        }
        this.paramForm.customerName = selCustomerObject.customerFullName
        this.paramForm.customerId = selCustomerObject.customerNo
      }
      this.showCustomerPicker = false
    },
    // 项目
    closeConnectProject (selProjectObject) {
      if (selProjectObject != null) {
        this.paramForm.projectCode = selProjectObject.projectCode
        this.paramForm.relatedProjectsNumber = selProjectObject.id
      }
      this.showProjectPicker = false
    },
    // 拜访报告
    closeConnectReport (selReprotObject) {
      if (selReprotObject != null) {
        this.paramForm.visitReportCode = selReprotObject.visitCode
        this.paramForm.visitReportNumber = selReprotObject.id
      }
      this.showVisitPicker = false
    },
    // 关联项目和关联拜访选择
    projectVisitPickerClick (type) {
      if (type === 'showProjectPicker') {
        if (this.$refs.projectRef) {
          this.$refs.projectRef.tableData = []
          this.$refs.projectRef.handleSure()
        }
        this[type] = true
      } else {
        if (this.$refs.visitRef) {
          this.$refs.visitRef.tableData = []
          this.$refs.visitRef.reload()
        }
        if (this.moduleId === 3102) {
          if (!this.disabled) {
            this[type] = true
          }
        } else {
          this[type] = true
        }
      }
    },
    // 检查数据
    checkData (data) {
      let flag = true
      if (data.taskUserId == null || data.taskUserId === '') {
        this.$toast('请选择负责人员！')
        flag = false
      }
      if (data.taskContent == null || data.taskContent === '') {
        this.$toast('请填写任务描述！')
        flag = false
      }
      if (data.taskRequestDate == null || data.taskRequestDate === '') {
        this.$toast('请选择截止时间！')
        flag = false
      }
      if (data.emergencyDegree == null || data.emergencyDegree === '') {
        this.$toast('请选择紧要程度！')
        flag = false
      }
      if (data.taskSource == null || data.taskSource === '') {
        this.$toast('请选择任务来源！')
        flag = false
      }
      if (data.itemType == null || data.itemType === '') {
        this.$toast('请选择事项类型！')
        flag = false
      }
      return flag
    },
    // 关闭协同选择
    xietongClose (userData, indexNumber, status) {
      if (status) {
        this.usersTaskSelect = userData
      }
    },
    // 负责人
    taskUserInfo (users, indexNumber, status) {
      if (status) {
        if (users != null && users.length > 0) {
          this.paramForm.taskUserId = users[0].uid
          this.paramForm.taskUser = users[0].name
        } else {
          if (users != null && users.length === 0) {
            this.paramForm.taskUserId = ''
            this.paramForm.taskUser = ''
          }
        }
      }
    },
    // 校验数据
    checkDataRe (data) {
      let flag = true
      if (data.result === '' || data.result === undefined) {
        this.$toast('请选择批阅动作！')
        flag = false
      } else {
        if (
          data.result === 'adjust_cancel' ||
          data.result === 'cancel' ||
          data.result === 'unpass' ||
          data.result === 'change' ||
          data.result === 'adjust' ||
          data.result === 'recall'
        ) {
          if (data.content === '' || data.content === undefined) {
            this.$toast('审批说明为空，无法提交！')
            flag = false
          }
        }
      }
      if (data.result === 'change') {
        if (data.taskUserId === '' || data.taskUserId === undefined) {
          this.$toast('请选择转办人！')
          flag = false
        }
      }
      return flag
    },
    // 添加审批数据
    saveReviewer (operReviewer) {
      this.$axios.post({
        domain: 'crmUrl',
        url: 'reviewer.saveReviewer',
        data: operReviewer,
        isShow:true,
        success: function (res) {
          if (res.errorCode === 200) {
            this.$toast.success('处理成功')
          } else {
            this.$toast.fail(res.msg)
          }
        }.bind(this)
      })
    },
    // 添加编辑
    submitForm (status, autoSave) {
      if (!autoSave && !this.checkData(this.paramForm)) {
        return
      }
      this.paramForm.status = status
      this.paramForm.isAuto = autoSave
      // 知会人员列表
      this.paramForm.informerParamList = []
      let informerParamList = []
      let userSelect = this.usersTaskSelect
      if (userSelect.length !== 0) {
        userSelect.forEach(v => {
          informerParamList.push({
            email: v.email,
            informerType: 1,
            userId: v.uid,
            userName: v.name
          })
        })
      }
      this.paramForm.informerParamList = informerParamList
      if (!this.isCallBack) {
        let operReviewer = this.$refs['operReviewer'].param
        if (this.handle) {
          operReviewer.reviewerType = 3104
          let flag = this.checkDataRe(operReviewer)
          if (!autoSave && !flag) {
            return
          }
        }
        let oper = this.paramForm.status === 'draft' ? '保存成功！' : '提交成功！'
        this.showLoading = true
        if(!autoSave){
           this.btns.map(v => {
             v.disabled = true
             v.name = v.param === this.paramForm.status ? '请稍后...' : v.name
           })
        }
        this.$axios.post({
          domain: 'crmUrl',
          url: 'task.saveTask',
          data: this.paramForm,
          requestType: 'body',
          success: function (res) {
            this.showLoading = false
            if (res.errorCode === 200) {
              this.btns.map(v => {
                v.disabled = false
                v.name = v.backupName
              })
              if (this.handle) {
                this.saveReviewer(operReviewer)
              }
              this.paramForm.id = res.data.id; //自动保存需要id
              if(!autoSave){
                this.returnLast(this.paramForm)
                this.$toast.success(oper)
              }
            } else {
              if(!autoSave){
                this.$toast.fail(res.msg)
              }
            }
            this.btns.map(v => {
              v.disabled = false
              v.name = v.backupName
            })
          }.bind(this)
        })
      } else {
        this.returnLast(this.paramForm)
      }
    },
    // 紧要程度
    onEmergencyConfirm (data) {
      this.paramForm.emergencyDegree = data.vaule
      this.paramForm.emergencyDegreeKey = data.key
      this.showemergencyPicker = false
    },
    // 任务提醒
    onNotifyConfirm (data) {
      this.paramForm.notifyWayId = data.vaule
      this.paramForm.notifyWayName = data.key
      this.showNotifyPicker = false
    },
    // 任务来源
    onSourceConfirm (data) {
      this.paramForm.taskSource = data.vaule
      this.paramForm.taskSourceKey = data.key
      this.showSourcePicker = false
    },
    defaultDate () {
      let nowDate = new Date()
      this.currentDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate())
      this.minDate = this.currentDate
    },
    // 截止时间
    onTimeConfirm (data) {
      data = new Date(data)
      this.paramForm.taskRequestDateFormat = this.formatDate(data)
      this.paramForm.taskRequestDate = data
      this.showTimePicker = false
    },
    // 事项类型组件
    onConItemfirm (data) {
      this.paramForm.itemTypeKey = data.key
      this.paramForm.itemType = data.vaule
      this.showItemPicker = false
    },
    // 时间格式化显示
    formatDate (data) {
      var year = `${data.getFullYear()}`
      var month = `${data.getMonth() + 1}`
      var day = `${data.getDate()}`
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      return year + '-' + month + '-' + day
    },
    // 返回上一页
    returnLast (data) {
      if (this.$route.path === '/newWork' || this.$route.path === '/newVisit') {
        this.$emit('taskData', data)
      } else {
        this.handleClose()
      }
      // let path = this.$route.path
      // if (path === '/newTask') {
      //   this.clearCache()
      //   this.$router.back(-1)
      // } else {
      //   this.$emit('taskData', data)
      // }
    },
    // 区分模块并赋默认值
    defaultTaskSource () {
      if (this.moduleId) {
        this.paramForm.modelId = this.moduleId
      }
      if (this.taskData) {
        this.paramForm = this.taskData
        this.initUser(this.taskData)
      }
      switch (this.moduleId) {
        // 项目
        case 3101:
          this.paramForm.taskSource = 'project'
          this.paramForm.taskSourceKey = '客户项目'
          break
        // 拜访报告
        case 3102:
          this.paramForm.taskSource = 'visit'
          this.paramForm.taskSourceKey = '拜访报告'
          this.showVisitPicker = false
          this.disabled = true
          break
        // 工作报告
        case 3103:
          this.paramForm.taskSource = 'work'
          this.paramForm.taskSourceKey = '工作报告'
          break
        // 任务
        case 3104:
          this.paramForm.taskSource = 'add'
          this.paramForm.taskSourceKey = '新增'
          this.isEdit = false
          break
      }
    },
    // 获取数据字典
    async getDict () {
      // 事项类型
      this.itemTypes = await commonSelectList.initDictDataPost(this, 'Crm_Event_Type')
      // 任务来源
      this.taskSources = await commonSelectList.initDictDataPost(this, 'Crm_Task_Source')
      // 紧要程度
      this.emergencys = await commonSelectList.initDictDataPost(this, 'Crm_Import_Level')
      // 查询客户
      this.customers = await commonSelectList.initGetCustomer(this)
      // 引用项目接口
      this.projects = await commonSelectList.initGetProjectList(this)
      // 引用拜访报告接口
      this.visits = await commonSelectList.initGetVisitList(this)
    },
    // 编辑回显数据
    getDetails () {
      if (this.$route.query.rowId) {
        this.paramForm.id = this.$route.query.rowId
        this.getTaskDetails()
        this.title = '编辑任务'
      }
    },
    // 根据任务ID获取其详情数据
    getTaskDetails () {
      this.$axios.post({
        domain: 'crmUrl',
        url: 'task.getTaskDetails',
        data: { id: this.paramForm.id },
        requestType: 'body',
        showLoad: false,
        success: function (res) {
          if (res.errorCode === 200) {
            let data = res.data
            this.paramForm = data
            this.initUser(data)
            this.detailInfo.busId = data.id
            this.detailInfo.status = data.status
            this.$refs.operReviewer.getOperReviewer(this.detailInfo)
          } else {
            this.$toast.fail(res.msg)
          }
        }.bind(this),
        error: function (res) {
          this.$toast.fail(res.msg)
        }
      })
    },
    initUser (data) {
      // 回显给负责人
      if (data.taskUserId != null && data.taskUserId !== '') {
        let usersSalesSelect = []
        let task = {}
        task.name = data.taskUser
        task.uid = data.taskUserId
        usersSalesSelect.push(task)
        this.usersSalesSelect = usersSalesSelect
        setTimeout(() => {
          this.$refs.awsOrgRef.refreshUser(usersSalesSelect)
        }, 500)
      }

      // 回显给组织架构,知会人员   informerParamList
      if (data.informerParamList != null && data.length !== 0) {
        let usersTaskSelect = []
        data.informerParamList.forEach(v => {
          v.name = v.userName
          v.uid = v.userId
          usersTaskSelect.push(v)
        })
        this.usersTaskSelect = usersTaskSelect
        setTimeout(() => {
          this.$refs.awsInfoOrgRef.refreshUser(usersTaskSelect)
        }, 500)
      }
    },
    //自动保存
    autoSaveForm(){
      let _this = this, autoSave=true;
      clearInterval(this.timeId);
      this.timeId = setInterval(()=>{
        this.submitForm('draft', autoSave);
        console.log('auto')
      }, 1000*30)

    },

  }
}
</script>

<style lang="scss" scoped>
.form-class{
    height: calc(100vh - 82px);
    overflow-y: auto;
    padding-bottom: 152px;
  }
.van-form {
  .row {
    padding: 10px;
    border-bottom: 1px solid #ddd;
    display: block;
    background-color: #fff;

    label {
      color: #646566;
      margin-right: 15px;
    }
  }
}

.van-textarea {
  border: 1px solid #f1f0f0;
}
.footer-btn {
  button {
    margin: 0px 2px;
  }
}
.van-cell__value {
  span {
    color: #c9c9c9;
    margin-right: 8px;
  }
}

.van-cell .van-cell__title span::after {
  position: absolute;
  margin: 0.08rem -0.10667rem 0 0;
  color: #ee0a24;
  font-size: 0.18667rem;
  content: "*";
}
</style>
