<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar :title="navTitle" />
			
      <view
        v-if="showNoData"
        :style="{backgroundImage: bgUrl('images/no_data.png')}"
        class="no-data">
        暂无数据
      </view>
			
      <view
        v-else class="container">
        <view
          v-if="detailData.taskData && detailData.taskData.length"
          class="task-contaienr">
          <view class="group-title-box">
            <view class="prev-badge" />
            <text>阶段工作</text>
          </view>
          <view class="task-content">
            <view
              v-for="(task, index) in detailData.taskData"
              :key="index"
              class="task-item"
              @click="changeTaskStatus(task)">
              <view :class="{over: task.isOk}" class="checkbox">
                <text v-if="task.isOk" class="icon wk wk-check" />
              </view>
							
              <view class="item-content">
                <view class="item-title" :class="{'over': task.isOk}">
                  <text v-if="task.isNull" class="required">
                    *
                  </text>
                  <text>{{ task.taskName }}</text>
                </view>
                <view
                  v-if="task.isOk && task.createUserName"
                  class="item-desc">
                  {{ task.createUserName }}于{{ task.createTime | formatTime }}完成
                </view>
              </view>
            </view>
          </view>
        </view>
				
        <view
          v-if="fieldList.length"
          class="form-container">
          <view class="group-title-box">
            <view class="prev-badge" />
            <text>表单信息</text>
          </view>
          <view class="form-content">
            <wk-form
              ref="fieldForm"
              :fields="fieldList"
              @change="formChange" />
          </view>
        </view>
				
        <view v-if="showAudit" class="examine-container">
          <wk-audit-add ref="wkAuditAdd" />
        </view>
      </view>

      <view
        v-if="!showNoData"
        class="footer-btn-group">
        <button
          class="button plain-btn"
          @click="handleToComment">
          反馈
          <template v-if="detailData.commentNum">
            （{{ detailData.commentNum }}）
          </template>
        </button>
        <button
          class="button"
          @click="handleSave(true)">
          保存草稿箱
        </button>
        <button
          class="button"
          @click="handleSave(false)">
          提交
        </button>
      </view>
    </view>
		
    <uni-popup
      ref="commentPopup"
      radius="20rpx 20rpx 0 0"
      type="bottom"
      @click.stop>
      <flow-comment-popup
        v-if="showCommentContent"
        :data-id="routerQuery.id"
        :comment-num="detailData.commentNum"
        @update="getData"
        @close="handleCloseComment" />
    </uni-popup>
  </view>
</template>

<script>
  import {
    QueryFlowDataInfoAPI,
    SaveFlowDataAPI
  } from '@/api/crm/flow.js'
  import { PreviewFiledName } from '@/api/examine.js'
	
  import FlowCommentPopup from './components/customFlow/flowCommentPopup.vue'
	
  import formMixins from '@/mixins/formMixins.js'
  import { deepCopy } from '@/utils/lib.js'
  import { isArray } from '@/utils/types.js'
  import moment from 'moment'
	
  export default {
    name: 'CustomFlowUpdate',
    filters: {
      formatTime(data) {
        return moment(data).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    components: {
      FlowCommentPopup
    },
    mixins: [formMixins],
    data() {
      return {
        loading: false,
        routerQuery: {},
        detailData: {},
				
        fieldList: [],
				
        showAudit: false,
        auditConditionFields: [],
        timer: null,
				
        showCommentContent: false,
        commandData: []
      }
    },
    computed: {
      navTitle() {
        const name = this.detailData.flowName || ''
        return `${name}阶段信息`
      },
      showNoData() {
        if (!this.detailData) return true
        if (
          this.detailData.taskData &&
          this.detailData.taskData.length
        ) return false
        if (this.fieldList.length) return false
        if (this.showAudit) return false
        return true
      }
    },
    onLoad(options) {
      this.routerQuery = options || {}
      this.getData()
    },
    methods: {
      bgUrl(val) {
        return `url(${this.$static(val)})`
      },

      getData() {
        QueryFlowDataInfoAPI({
          dataId: this.routerQuery.id
        }).then(res => {
          this.detailData = res
					
          const list = deepCopy(this.detailData.fieldData || [])
          console.log('list： ', list)
          list.forEach(field => {
            field.value = this.mixinsFormatFieldValue(field)
          })
          this.fieldList = list
					
          if (res.examineId) {
            this.getAuditList()
          }
        }).catch(() => {})
      },
			
      /**
       * 获取审批流程条件
       */
      getAuditList() {
        PreviewFiledName({
          examineId: this.detailData.examineId
        }).then(res => {
          this.showAudit = res !== null
          if (!this.showAudit) return
          const mapIns = new Map()
          this.auditConditionFields = res.filter(o =>	!mapIns.has(o.fieldId) && mapIns.set(o.fieldId, 1))
          // console.log('PreviewFiledName: ', this.auditConditionFields)
          this.$nextTick(() => {
            const dataMap = {}
            this.auditConditionFields.forEach(o => {
              const findRes = this.fieldList.find(f => f.fieldName === o.fieldName)
              if (findRes) {
                let value = findRes.value
			
                switch (findRes.formType) {
                case 'select':
                  if (this.$isEmpty(value)) value = ''
                  if (isArray(value)) {
                    value = value[0].value
                  }
                  break
                case 'checkbox':
                  if (this.$isEmpty(value)) value = ''
                  if (isArray(value)) {
                    value = value.map(o => o.value).join(',')
                  }
                  break
                default:
                  value = this.$isEmpty(value) ? '' : value
                }
                o._val = value
                dataMap[o.fieldName] = value
              }
            })
			
            this.$refs.wkAuditAdd.getAuditInfo({
              examineId: this.detailData.examineId,
              dataMap
            })
          })
        }).catch(() => {})
      },
			
      /**
       * 根据条件更新审批流程
       * @param {Object} field
       * @param {Object} value
       */
      changeAuditFlow(field, value) {
        if (!this.showAudit) return
        const findRes = this.auditConditionFields.find(o => o.fieldName === field.fieldName)
        if (!findRes) return
        switch (field.formType) {
        case 'select':
          if (this.$isEmpty(value)) value = ''
          if (isArray(value)) {
            value = value[0].value
          }
          break
        case 'checkbox':
          if (this.$isEmpty(value)) value = ''
          if (isArray(value)) {
            value = value.map(o => o.value).join(',')
          }
          break
        default:
          value = this.$isEmpty(value) ? '' : value
        }
        findRes._val = value
        const dataMap = {}
        this.auditConditionFields.forEach(o => {
          if (o.hasOwnProperty('_val')) {
            dataMap[o.fieldName] = this.$isEmpty(o._val) ? '' : o._val
          } else {
            dataMap[o.fieldName] = ''
          }
        })
        this.$nextTick(() => {
          this.$refs.wkAuditAdd.getAuditInfo({
            examineId: this.detailData.examineId,
            dataMap
          })
        })
      },
			
      /**
       * 修改任务状态
       */
      changeTaskStatus(task) {
        const status = task.isOk === 1 ? 0 : 1
        this.$set(task, 'isOk', status)
      },
			
      /**
       * 修改表单字段值
       * @param {Object} data
       */
      formChange(data) {
        console.log('value change: ', data)
        this.changeAuditFlow(data.field, data.value)
      },
			
      /**
       * 反馈信息弹窗
       */
      handleToComment() {
        this.showCommentContent = true
        this.$refs.commentPopup.open()
      },
			
      /**
       * 关闭反馈弹窗
       */
      handleCloseComment() {
        this.showCommentContent = false
        this.$refs.commentPopup.close()
      },

      handleSave(isDraft = false) {
        if (this.loading) return
        this.loading = true
        const saveForm = {
          id: this.detailData.id, // 阶段id
          flowId: this.detailData.flowId, // 阶段流程id
          status: isDraft ? 0 : 1 // 0 保存草稿 1 提交
        }

        // 任务
        saveForm.taskData = deepCopy(this.detailData.taskData || [])
        if (saveForm.taskData.length) {
          const filterArr = saveForm.taskData.filter(task => {
            return task.isNull && !task.isOk
          })
          if (filterArr.length) {
            const msg = filterArr.map(o => o.taskName).join('，')
            this.$toast(`阶段工作${msg}为必做`)
            return
          }
          saveForm.taskData.forEach(task => {
            delete task.companyId
          })
        }
				
        // 审批信息
        if (!isDraft && this.showAudit) {
          const data = this.$refs.wkAuditAdd.getSaveData()
          if (data === null) {
            this.loading = false
            return
          }
          const dataMap = {}
          this.auditConditionFields.forEach(o => {
            if (o.hasOwnProperty('_val')) {
              dataMap[o.fieldName] = this.$isEmpty(o._val) ? '' : o._val
            }
          })
				
          saveForm.examineFlowData = {
						...data,
						categoryId: this.detailData.examineId,
						dataMap
          }
        }
				
        // 表单
        const fieldFormInstance = this.$refs.fieldForm
        if (fieldFormInstance) {
          fieldFormInstance.getForm().then(form => {
            saveForm.fieldData = form.field
            this.submitForm(saveForm)
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.submitForm(saveForm)
        }
      },
			
      /**
       * 提交流程表单
       * @param {Object} form
       */
      submitForm(form) {
        // console.log('submit form: ', form)				
        this.loading = true
        SaveFlowDataAPI(form).then(res => {
          this.loading = false
          this.$refreshAndToPrev(this, true)
        }).catch(() => {
          this.loading = false
        })
      }
    }
  }
</script>

<style scoped lang="scss">
	.checkbox {
		width: 32rpx;
		height: 32rpx;
		border: 1rpx solid #CCCCCC;
		border-radius: 6rpx;
		overflow: hidden;
		@include center;
		.icon {
			font-size: 24rpx;
			line-height: 1;
			color: white;
		}
		&.over {
			background-color: $theme-color;
			border-color: $theme-color;
		}
	}
	
	.no-data {
		width: 100%;
		flex: 1;
		text-align: center;
		font-size: 26rpx;
		color: #BBBBBB;
		background-position: center 200rpx;
		background-repeat: no-repeat;
		background-size: 200rpx;
		padding-top: 430rpx;
	}

	.container {
		flex: 1;
		background-color: white;
		overflow: auto;
		padding: 0 30rpx 20rpx;
		
		.group-title-box {
			font-size: $wk-font-medium;
			padding: 18rpx 0;
			@include left;
			.prev-badge {
				width: 10rpx;
				height: 30rpx;
				border-radius: 10rpx;
				background-color: $theme-color;
				margin-right: 15rpx;
			}
		}

		.task-contaienr {
			.task-content {
				padding-left: 15rpx;
				margin-top: -15rpx;
				.task-item {
					padding: 20rpx 0;
					display: flex;
					align-items: flex-start;
					justify-content: flex-start;
					.item-content {
						flex: 1;
						margin-left: 25rpx;
						.required {
							color: $error;
						}
					}
					.item-desc {
						font-size: $wk-font-sm;
						color: $light;
						margin-top: 5rpx;
					}
				}
			}
		}
		
		.form-container {
			.form-content {
				margin: -15rpx -30rpx 0 -30rpx;
			}
		}
		
		.examine-container {
			margin: 0 -30rpx;
		}
		
		
	}
	
	.footer-btn-group {
		.button {
			margin: 0 10rpx;
		}
		.plain-btn {
			color: $theme-color;
			border: 1px solid $theme-color;
			background-color: white;
		}
	}
</style>