<template>
  <view class="pg-complete">
    <complete-check
      :show="completeCheck.status"
      :list-data="completeCheck.result"
      :pass="pass"
      @close="closeCheckResult"
      @confirm="confirm"
      :confirm-button-text="completeCheck.confirmText"
      :cancel-button-text="completeCheck.cancelText"
    ></complete-check>
    <view class="com-content">
      <u-navbar
        :background="{ background: '#2272FF' }"
        back-icon-color="#fff"
        :title-size="32"
        title-color="#fff"
        :border-bottom="false"
        :title="list[tabIndex].panelName"
        title-bold
        :custom-back="backGo"
      ></u-navbar>
      <u-tabs
        class="order-tabs"
        ref="tabs"
        :current="current"
        name="panelName"
        :list="tabList"
        @change="swichMenu"
        bg-color="#2272FF"
        inactive-color="#a6c6ff"
        active-color="#fff"
        height="80"
        font-size="32"
      ></u-tabs>
      <view class="u-menu-wrap">
        <scroll-view
          :scroll-top="scrollRightTop"
          style="height: 100%"
          scroll-y
          scroll-with-animation
          scroll-anchoring
          class="right-box"
          @scroll="rightScroll"
          :scroll-into-view="itemId"
        >
          <u-form :model="form" ref="uForm">
            <template
              v-for="(groupItem, groupIndex) in list.length > 0
                ? list[tabIndex].items
                : []"
            >
              <view
                class="class-item"
                :id="'item' + groupIndex"
                :key="groupIndex"
              >
                <view class="title">{{ groupItem.name }}</view>
                <view class="class-bd">
                  <u-form-item
                    v-for="(item, itemIndex) in groupItem.items"
                    :key="itemIndex"
                    label-position="top"
                    :prop="item.fieldsName"
                    :border-bottom="false"
                    v-show="
                      checkFields(item.fieldsName) &&
                        ((readOnly &&
                          !$u.test.isEmpty(form[item.fieldsName])) ||
                          !readOnly)
                    "
                    :id="`item${item.fieldsId}`"
                  >
                    <view
                      class="label"
                      v-if="!hiddenTitle.includes(item.formType)"
                    >
                      <image
                        class="item-image"
                        :src="mixingImage"
                        v-if="item.required"
                      ></image>
                      {{ item.fieldsTitle }}
                    </view>
                    <template v-if="item.fieldsType">
                      <xh-input
                        v-if="item.formType === 'input'"
                        :groupIndex="groupIndex"
                        :type="item.inputType"
                        :itemIndex="itemIndex"
                        :item="item"
                        :value="form[item.fieldsName] || ''"
                        :disabled="readOnly || item.disabled || false"
                        :slotContent="item.fieldsInfo"
                        @value-change="fieldValueChange"
                      >
                      </xh-input>
                      <xh-multi-input
                        v-if="item.formType === 'multiinput'"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :value="form[item.fieldsName] || ''"
                        :disabled="readOnly"
                        @value-change="fieldValueChange"
                      >
                      </xh-multi-input>
                      <xh-radio
                        v-if="item.formType === 'radio'"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :value="form[item.fieldsName] || ''"
                        :disabled="readOnly || item.disabled || false"
                        @value-change="fieldValueChange"
                      >
                      </xh-radio>
                      <xh-checkbox
                        v-if="item.formType === 'checkbox'"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :value="form[item.fieldsName] || ''"
                        :disabled="readOnly"
                        @value-change="fieldValueChange"
                      >
                      </xh-checkbox>
                      <xh-select
                        v-if="item.formType === 'select'"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :value="form[item.fieldsName] || ''"
                        :disabled="readOnly"
                        @value-change="fieldValueChange"
                      >
                      </xh-select>
                      <xh-specifications
                        v-if="item.formType === 'select-new-page'"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :value="form[item.fieldsName] || ''"
                        :disabled="readOnly"
                        @value-change="fieldValueChange"
                      >
                      </xh-specifications>
                      <view v-if="item.formType === 'file'">
                        <xh-files
                          :ref="`fileChild${groupIndex}${itemIndex}`"
                          :groupIndex="groupIndex"
                          :itemIndex="itemIndex"
                          :item="item"
                          :partnerCompanyId="partnerCompanyId"
                          :categoryId="categoryId"
                          :value="form[item.fieldsName] || []"
                          :disabled="readOnly"
                          @value-change="fieldValueChange"
                        >
                          <template v-slot>
                            <view class="img-list" v-if="!readOnly">
                              <u-image
                                class="pic"
                                width="160rpx"
                                height="160rpx"
                                :border-radius="10"
                                @click="
                                  selectUpload(
                                    JSON.stringify(item),
                                    groupIndex,
                                    itemIndex
                                  )
                                "
                                :src="uploadImage"
                              ></u-image>
                            </view>
                          </template>
                        </xh-files>
                      </view>

                      <xh-location
                        v-if="item.formType === 'location'"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :value="form[item.fieldsName] || ''"
                        :disabled="readOnly"
                        @value-change="fieldValueChange"
                      >
                      </xh-location>
                      <xh-scan
                        v-if="item.formType === 'scan'"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :value="form[item.fieldsName] || ''"
                        :disabled="readOnly"
                        @value-change="fieldValueChange"
                      >
                      </xh-scan>
                      <xh-service-measure
                        v-if="item.formType === 'servicemeasure'"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :orderId="orderId"
                        :categoryId="categoryId"
                        :orderServiceType="orderServiceType"
                        :specificationId="form['specificationId'] || 0"
                        :value="form[item.fieldsName]"
                        :disabled="readOnly"
                        @value-change="fieldValueChange"
                      >
                      </xh-service-measure>
                      <xh-time
                        v-if="item.formType === 'time'"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :value="form[item.fieldsName] || ''"
                        :disabled="readOnly"
                        @value-change="fieldValueChange"
                      >
                      </xh-time>
                      <xh-service-more
                        v-if="item.formType === 'form'"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :order-id="orderId"
                        :value="form[item.fieldsName] || ''"
                        :disabled="readOnly"
                        @value-change="fieldValueChange"
                      >
                      </xh-service-more>
                      <xh-label
                        v-if="item.formType === 'label'"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :value="form[item.fieldsName] || ''"
                      >
                      </xh-label>
                      <xh-parts
                        ref="fileChildParts"
                        v-if="item.formType === 'parts'"
                        :categoryId="categoryId"
                        :brandId="brandId"
                        :order-id="orderId"
                        :orderNumber="orderNumber"
                        :groupIndex="groupIndex"
                        :itemIndex="itemIndex"
                        :item="item"
                        :value="form[item.fieldsName] || ''"
                        :disabled="readOnly"
                        :maintainStep="list[tabIndex].panelFieldsName"
                        @value-change="fieldValueChange"
                      >
                      </xh-parts>
                    </template>
                  </u-form-item>
                </view>
              </view>
            </template>
          </u-form>
        </scroll-view>
      </view>
      <view
        :class="[
          'btn-wrap',
          'flex-xc',
          { 'btn-bottom': tabIndex > 0, 'read-only': readOnly },
        ]"
      >
        <u-button
          class="btn-submit"
          v-if="!readOnly"
          @click="saveComplete"
          type="primary"
          shape="circle"
          :custom-style="customStyle"
          :hover-class="submitStatus ? '' : 'none'"
        >
          暂存
        </u-button>
        <u-button
          class="btn-submit"
          @click="nextStep"
          :custom-style="buttonStyle"
          type="primary"
          shape="circle"
          :hover-class="submitStatus ? '' : 'none'"
        >
          {{
            tabIndex === list.length - 1
              ? readOnly
                ? '返回列表'
                : '提交'
              : readOnly
              ? '查看下一步'
              : '下一步'
          }}
        </u-button>
      </view>
    </view>
    <u-toast ref="uToast" />
    <take-photo
      v-if="takeStatus"
      @close="closeTake"
      :upload="false"
      :currentItem="currentItemDate"
    ></take-photo>
    <u-action-sheet
      :list="carmeraList"
      v-model="maskShow"
      :cancel-btn="true"
      @click="uploadSelect"
    ></u-action-sheet>
    <upload-progress />
  </view>
</template>
<script>
import XhInput from '@/components/createCom/XhInput.vue'
import XhMultiInput from '@/components/createCom/XhMultiInput.vue'
import XhRadio from '@/components/createCom/XhRadio.vue'
import XhCheckbox from '@/components/createCom/XhCheckbox.vue'
import XhSelect from '@/components/createCom/XhSelect.vue'
import XhSpecifications from '@/components/createCom/XhSpecifications.vue'
import XhFiles from '@/components/createCom/XhFiles.vue'
import XhLocation from '@/components/createCom/XhLocation.vue'
import XhScan from '@/components/createCom/XhScan.vue'
import XhTime from '@/components/createCom/XhTime.vue'
import XhServiceMeasure from '@/components/createCom/XhServiceMeasure.vue'
import XhServiceMore from '@/components/createCom/XhServiceMore'
import XhLabel from '@/components/createCom/XhLabel'
import XhParts from '@/components/createCom/XhParts'
import takePhoto from '@/components/take/index.vue'
import baseFile from '@/components/upload/index'

// 表单类型map
const formType = new Map([
  ['text', ['input', 'textarea']],
  ['password', ['password', 'input']],
  ['textarea', ['input', 'digit']],
  ['number', ['input', 'digit']],
  ['decimal', ['input', 'digit']],
  ['double', ['input', 'digit']],
  ['integer', ['input', 'digit']],
  ['string', ['input', 'text']],
  ['jscode', ['input', 'text']],
  ['multiinput', ['multiinput', 'text']],
  ['select', ['select', 'text']],
  ['specifications', ['select-new-page', 'text']],
  ['radio', ['radio', 'text']],
  ['checkbox', ['checkbox', 'text']],
  ['file', ['file', 'text']],
  ['photos', ['file', 'text']],
  ['location', ['location', 'text']],
  ['scan', ['scan', 'text']],
  ['machine_code', ['scan', 'text']],
  ['service_measures', ['servicemeasure', 'text']],
  ['time', ['time', 'text']],
  ['date', ['time', 'text']],
  ['form', ['form', 'text']],
  ['label', ['label', 'text']],
  ['parts', ['parts', 'text']],
])

/**
 * modal 弹窗校验
 * @description 用于校验下一步的动作
 * @property {String} name 当前的订单阶段
 * @property {Boolean} pass 是否通过校验
 * @property {String}} type 是否有二次勘测或二次安装
 * @property {submit} submit 提交或下一步
 */
const actions = (name, pass, type, submit) => {
  const handerProgrom = {
    perfect: {
      confirmText: '去完善',
      action: 'handerProgrom',
    },
    appointment: {
      confirmText: '好的，再次预约',
      action: 'appointment',
    },
    next: {
      confirmText: '下一步',
      action: 'nextAction',
    },
    noPerfectSubmit: {
      confirmText: '去完善',
      action: 'handerProgrom',
      cancelText: '部分提交',
      cancelAction: 'appointment',
    },
    submit: {
      confirmText: '提交',
      action: 'orderFinish',
    },
    confirm: {
      confirmText: '确定',
      action: 'nextAction',
      cancelText: '取消',
      cancelAction: 'closeResult',
    },
  }
  if (name === 'partnerInspectItem') {
    // 勘察
    if (!pass) return handerProgrom.perfect
    return type
      ? type === '01'
        ? handerProgrom.next
        : handerProgrom.appointment
      : handerProgrom.perfect
  } else if (name === 'partnerInstallItem') {
    // 安装
    let hander = ''
    switch (type) {
      case '01': // 安装完成
        hander = !pass ? handerProgrom.perfect : handerProgrom.next
        break
      case '02': // 二次安装
        hander = !pass
          ? handerProgrom.noPerfectSubmit
          : handerProgrom.appointment
        break
      case '03': //不安装
        hander = handerProgrom.confirm
        break
      default:
        hander = handerProgrom.perfect
        break
    }
    return hander
  } else {
    // 基础信息
    if (!pass) return handerProgrom.perfect
    return submit ? handerProgrom.submit : handerProgrom.next
  }
}


const fields = {
  'paymentMethodsType': { // 基本信息-不需要收款
    fieldsName: ['actualPaid', 'eSerialNum'],
    value: '03'
  },
  'usePart': { // 维修工单-是否使用配件
    fieldsName: ['partName'],
    value: '02'
  },
  'getMoney': { // 维修工单-是否收款
    fieldsName: ['feeValue', 'feeProject'],
    value: '02'
  }
}

const fieldsNameArr = Object.values(fields).map(v => v.fieldsName).reduce((acc, cur) => [...acc, ...cur], [])

export default {
  data() {
    return {
      hiddenTitle: ['location', 'form', 'label', 'parts'],
      orderId: 0,
      categoryId: 0,
      brandId: 0,
      orderNumber: '',
      orderServiceType: '',
      inGuaranteePeriod: '',
      partnerCompanyId: '',
      auditResults: [],
      list: [],
      tabIndex: 0,
      scrollTop: 0, //tab标题的滚动条位置
      oldScrollTop: 0,
      current: 0, // 预设当前项的值
      menuHeight: 0, // 左边菜单的高度
      menuItemHeight: 0, // 左边菜单item的高度
      itemId: '', // 栏目右边scroll-view用于滚动的id
      oldItemId: '',
      menuItemPos: [],
      arr: [],
      scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
      timer: null, // 定时器
      form: {},
      submitBtnStatus: false,
      completeCheck: {
        status: false,
        resulut: [],
        confirmText: '去完善',
        cancelText: '',
        action: '',
        cancelAction: '',
      },
      waitHandlerPanelIndex: 0,
      waitHandlerGroupIndex: 0,
      waitHandlerEleIndex: 0,
      pass: false,
      // 上传组件相关
      carmeraList: [
        {
          text: '相册',
        },
        {
          text: '拍照',
        },
      ],
      maskShow: false,
      takeStatus: false,
      currentItemDate: {},
      photoItem: {},
      maintainStep: 'partnerInspectItem',
      orderStatus: '',
      // showTab: true,
    }
  },
  components: {
    XhInput,
    XhMultiInput,
    XhRadio,
    XhCheckbox,
    XhSelect,
    XhSpecifications,
    XhFiles,
    XhLocation,
    XhScan,
    XhTime,
    XhServiceMeasure,
    XhServiceMore,
    XhLabel,
    XhParts,
    'take-photo': takePhoto,
  },
  mixins: [baseFile],
  onLoad(option) {
    getApp().trackPage('订单完工信息页')
    if (option) {
      this.orderNumber = option.orderNumber
      this.maintainStep = option.maintainStep
      this.orderId = option.orderId
      this.categoryId = option.categoryId
      this.brandId = option.brandId
      this.orderServiceType = decodeURIComponent(option.orderServiceType)
      this.inGuaranteePeriod = option.inGuaranteePeriod
      this.partnerCompanyId = option.partnerCompanyId
      this.orderStatus = option.orderStatus
      this.auditResults = option?.auditResults
        ? option?.auditResults.split(',')
        : []
    }
    this.getCompleteData()
  },
  updated() {
    //console.log(this.form.name, 'form.name')
  },
  computed: {
    exception() {
      return this.orderStatus == '86'
    },
    readOnly() {
      return (
        [80, 81, 83, 85, 87, 89, 88, 110].indexOf(Number(this.orderStatus)) !=
        -1
      )
    },
    tabList() {
      // 没有数据的时候tab要有占位数据，不然有页面有晃动
      return this.list.length > 0
        ? this.list[this.tabIndex].items
        : [{ name: '' }]
    },
    mixingImage() {
      return process.uniEnv.qn_base_url + 'mixing.png'
    },
    uploadImage() {
      return process.uniEnv.qn_base_url + 'upload-file.png'
    },
    buttonStyle() {
      return {
        color: '#FFFFFF',
        'background-color': '#2272FF;',
        width: '300rpx',
        height: '104rpx',
        'font-size': '32rpx',
        'font-weight': 'bold',
        'margin-left': '50rpx',
      }
    },
    customStyle() {
      return {
        'background-color': '#D1D4D4',
        width: '300rpx',
        height: '104rpx',
        'background-color': 'transparent',
        border: '1px solid #2272FF',
        color: '#2272FF',
        'font-weight': 'bold',
        'font-size': '32rpx',
      }
    },
    show200() {
      return (
        this.form.paymentMethodsType && this.form.paymentMethodsType != '03'
      )
    },
    // 从订单管理和浏览记录进来，不跳转到订单列表，而是后退到订单管理和浏览记录
    completeBack() {
      let pages = getCurrentPages()
      var i = 0
      for (var item of pages) {
        if (
          ['/pages/mine/history/index', '/pages/mine/order/index'].indexOf(
            item.$page?.fullPath.split('?')[0]
          ) != -1
        ) {
          return pages.length - i - 1
        }
        i++
      }
      return 0
    },
  },
  methods: {
    checkFields(name) {
      let status = true
      if (fieldsNameArr.includes(name)) {
        Object.entries(fields).forEach(v => {
          if (v[1].fieldsName.includes(name)) {
            status = this.form[v[0]] ? this.form[v[0]] !== v[1].value : false
          }
        })
      }
      return status
    },
    getCompleteData() {
      //获取工单配置的完工项目
      uni.showLoading({
        title: '加载中',
      })
      if (this.orderId) {
        this.$u.api.getCompleteConfigAndData(this.orderId).then((res) => {
          if (res.code == 200) {
            this.initData(res)
          } else {
            this.$refs.uToast.show({
              title: res.message || res.data,
              type: 'error',
            })
          }
        })
      }
    },
    initData(res) {
      this.form = res.data.value || {}
      this.loadOrderDetail()
      const data = Object.create(res.data.config, {})
      const list = data.sort((a, b) => a.order - b.order)
      if (this.readOnly) this.tabIndex = 0
      
      list.forEach((item, index) => {
        if (this.maintainStep === item.panelFieldsName && !this.readOnly) {
          this.tabIndex = index
        }
        item.items.forEach((v) => {
          v.items.forEach((d) => {
            const type = d.fieldsType.toLocaleLowerCase()
            const formMap = formType.get(type) || formType.get('text')
            d.formType = formMap[0]
            d.inputType = formMap[1]
            if (fieldsNameArr.includes(d.fieldsName)) {
              d.required =  this.checkFields(d.fieldsName)
            }

            if (d.fieldsName === 'pipe' || d.fieldsName === 'pipeUseLength') {
              // 申请费用计算
              this.calcMoney()
            }

            if (d.fieldsName === 'materialList') {
              d.subtitle = '(必填项)'
            }
            if (d.fieldsName === 'craftList') {
              d.subtitle = '(若有增项，则为必填项)'
            }
          })
        })
      })

      // this.showTab = this.list.length > 1
      // 异常单处理
      if (this.exception) {
        if (this.auditResults.length === 0) {
          this.$refs.uToast.show({
            title: '未找到不通过项',
            type: 'error',
            back: true,
          })
        }
        this.checkCompleteError(list)
      } else {
        this.list = Object.freeze(list)
      }
      uni.hideLoading()
    },
    loadOrderDetail() {
      if (
        !this.$u.test.isEmpty(this.form) &&
        this.form.hasOwnProperty('installComfirmTime') &&
        this.$u.test.isEmpty(this.form.installComfirmTime)
      ) {
        this.$u.api.orderDetail(null, this.orderId).then((res) => {
          if (res.code == 200) {
            if (!this.$u.test.isEmpty(res.data.checkInDateTime)) {
              this.$set(
                this.form,
                'installComfirmTime',
                this.moment(res.data.checkInDateTime).format('YYYY-MM-DD')
              )
            }
          }
        })
      }
    },
    checkCompleteError(list) {
      // 异常单定位错误项
      let errArr = []
      list.forEach((panel, panelIndex) => {
        panel.items.forEach((group, groupIndex) => {
          group.items.forEach((ele, eleIndex) => {
            if (this.auditResults.includes(ele.fieldsName)) {
              const errGroup = {
                componentType: group.componentType,
                name: group.name,
                items: ele,
              }
              if (ele.fieldsName === 'orderSpareParts') {
                const index = errArr.findIndex(v => v.name === '备件信息' || v.name === '物料信息')
                if (index > -1) return
              }
              errArr.push(errGroup)
            }
          })
        })
      })
      // 图片分组
      const result = errArr.reduce((groups, item) => {
        let groupFound = groups.find((arrItem) => item.name === arrItem.name)
        if (groupFound) {
          groupFound.componentType = item.componentType
          if (groupFound.items.indexOf(item.items) == -1) {
            //去重
            groupFound.items.push(item.items)
          }
        } else {
          //不要直接在原来的对象修改，新建对象
          let newGroup = {
            name: item.name,
            componentType: item.componentType,
            items: [item.items],
          }
          groups.push(newGroup)
        }
        return groups
      }, [])

      let index = list.length++
      list[index] = {
        order: index + 1,
        panelFieldsName: 'error',
        panelName: '异常处理',
        items: result,
      }
      this.list = Object.freeze(list)
      this.tabIndex = index
    },

    handleSaveData() {
      let param = {}
      const name = this.list[this.tabIndex].panelFieldsName
      this.list.forEach((panel) => {
        param[panel.panelFieldsName] = []
        panel.items.forEach((group) => {
          group.items.forEach((ele) => {
            if (name === 'partnerInspectItem') {
              if (!this.form?.installationMethodType) {
                this.$set(
                  this.form,
                  'installationMethodType',
                  this.form.installType
                )
              }
            }
            if (this.form[ele.fieldsName]) {
              param[panel.panelFieldsName].push({
                fieldsName: ele.fieldsName,
                fieldsType: ele.fieldsType,
                fieldsValue: this.form[ele.fieldsName],
                required: ele.required,
              })
            }
          })
        })
      })
      return param
    },
    saveComplete() {
      // 保存完工信息
      // this.submitParts() // 不调这个接口；没完工不能调提交配件
      const param = this.handleSaveData()
      this.$u.api.saveCompleteData(param, this.orderId).then((res) => {
        if (res.code == 200) {
          this.$refs.uToast.show({
            title: '保存成功',
            type: 'success',
          })
        } else {
          this.$refs.uToast.show({
            title: res.data || res.message,
            type: 'error',
          })
        }
      })
    },
    checkCompleteItem() {
      let checkResult = []
      let pass = true
      let first = true
      const lists = this.tabList
      console.log("lists", lists)
      lists.forEach((group, groupIndex) => {
        const checkRequired = group.items.some((v) => v.required)
        if (checkRequired) {
          let panelResult = {
            label: group.name,
            submitted: 0,
            required: 0,
            pass: true,
          }
          group.items.forEach((ele, eleIndex) => {
            if (ele.fieldsType == 'PARTS') {
              console.log("ele", ele)
            }
            if (ele.required) {
              panelResult.required++
              let value = this.form[ele.fieldsName]
              // "ele.fieldsName != 'eSerialNum' || value.length == 8"  意思是： "非付款流水号 || 8位付款流水号"
              if (value && !Array.isArray(value) && (ele.fieldsName != 'eSerialNum' || value.length == 8)) {
                  panelResult.submitted++
              } else if (value && Array.isArray(value) && value.length > 0) {
                if (ele.fieldsName === 'materialList') {
                  let hasMate = false
                  let mateRow = value.find((mate) => {
                    if (mate.hasOwnProperty('useLength')) {
                      hasMate = true
                      return !this.$u.test.isEmpty(mate.useLength)
                    }
                  })
                  if (!hasMate || !this.$u.test.isEmpty(mateRow)) {
                    panelResult.submitted++
                  }
                } else {
                  panelResult.submitted++
                }
              } else if (first) {
                // 记录第一个 为空 并且需要必填的项 用于定位
                first = false
                this.waitHandlerPanelIndex = this.tabIndex
                this.waitHandlerGroupIndex = groupIndex
                this.waitHandlerEleIndex = eleIndex
                this.oldItemId = `item${ele.fieldsId}`
              }
            }
          })
          panelResult.pass = panelResult.required <= panelResult.submitted
          pass = pass && panelResult.pass
          checkResult.push(panelResult)
        }
      })

      this.completeCheck.result = checkResult
      return pass
    },
    closeResult() {
      
    },
    // 检查结果窗口取消回调
    closeCheckResult() {
      this.completeCheck.status = false
      this[this.completeCheck.cancelAction]()
    },
    // 检查结果窗口 确认回调
    confirm() {
      this.completeCheck.status = false
      this[this.completeCheck.action]()
    },
    // 去完善
    handerProgrom() {
      this.locationCompleteItem(
        this.waitHandlerPanelIndex,
        this.waitHandlerGroupIndex,
        this.waitHandlerEleIndex
      )
    },
    // 去预约
    async appointment() {
      const save = await this.nextStepSaveData()
      if (save) {
        if (this.completeBack) {
          // 从订单管理和浏览记录进来
          uni.navigateBack({
            delta: this.completeBack,
          })
        } else {
          uni.reLaunch({
            url: '/pages/index/order?type=waitAppointment',
          })
        }
      }
    },
    // 下一步动作
    async nextAction() {
      const save = await this.nextStepSaveData()
      if (save) {
        this.nextTab()
      }
    },
    nextTab() {
      if (this.tabIndex < this.list.length - 1) {
        this.tabIndex++
        this.arr = []
        this.scrollRightTop = 0
        this.current = 0
        //this.itemId = ''
        //const itemId = this.list[this.tabIndex].items[0].items[0].fieldsId
        //this.oldItemId = `item${itemId}`
        this.$nextTick(async () => {
          await this.swichMenu(0)
        })
      }
    },

    // 下一步弹窗处理
    nextStep() {
      if (this.readOnly) {
        if (this.tabIndex === this.list.length - 1) {
          uni.navigateBack()
        } else {
          this.nextTab()
        }
        return
      }
      this.pass = this.checkCompleteItem()

      const name = this.list[this.tabIndex].panelFieldsName
      const type =
        name === 'partnerInspectItem'
          ? this.form.inspectConclusionType
          : this.form.constructionConclusionType
      const submit = this.tabIndex === this.list.length - 1
      const result = actions(name, this.pass, type, submit)

      this.completeCheck.status = true
      this.completeCheck.confirmText = result.confirmText
      this.completeCheck.action = result.action
      this.completeCheck.cancelText = result.cancelText || ''
      this.completeCheck.cancelAction = result.cancelAction || ''
    },
    // 下一步数据保存
    nextStepSaveData() {
      const params = {
        maintainFields: this.handleSaveData(),
        currentStep: this.list[this.tabIndex].panelFieldsName,
        nextStep: this.list[this.tabIndex + 1].panelFieldsName,
        version: 2,
      }
      uni.showLoading({
        title: '加载中',
      })
      return this.$u.api.completeNextStep(params, this.orderId).then((res) => {
        uni.hideLoading()
        if (res.code == 200) {
          return Promise.resolve(true)
        } else {
          this.$refs.uToast.show({
            title: res.message || res.data,
            type: 'error',
          })
          return Promise.resolve(false)
        }
      })
    },
    locationCompleteItem(panelIndex, groupIndex, eleIndex) {
      // 页面定位到某一项
      this.tabIndex = panelIndex
      this.current = groupIndex
      this.itemId = ''
      this.$nextTick(function() {
        if (this.oldItemId) this.itemId = this.oldItemId
      })
    },
    // 提交配件信息
    submitParts() {
      return new Promise((resolve, reject) => {
        if (this.form.orderSpareParts) {
          const orderSpareParts = JSON.parse(this.form.orderSpareParts)
          const lists = orderSpareParts.filter((v) => v.quantity > 0)
          const params = {
            workOrderId: this.orderId,
            applyType: '10',
            parts: lists ? JSON.stringify(lists) : '',
          }
          this.$u.api.createParts(params).then((res) => {
            if (res.code !== 200) {
              this.$refs.uToast.show({
                title: res.data,
                type: 'error',
              })
              resolve(false)
            }
            resolve(true)
          })
        } else {
          resolve(true)
        }
      })
    },
    // 提交订单
    orderFinish() {
      const param = this.handleSaveData()
      // 完工事件埋点
      getApp().track('order_finish', {
        id: this.vuex_user.id,
        mobile: this.vuex_user.mobile,
        orderId: Number(this.orderId),
      })
      this.$u.api.saveCompleteData(param, this.orderId).then(async (res) => {
        if (res.code == 200) {
          //完工项信息保存成功再次完工工单
          // if (!this.exception) { // 核销配件
          //   const submitPart = await this.submitParts()
          //   if (!submitPart) return
          // }

          if (this.inGuaranteePeriod === 'Y') {
            this.$u.api.inOrderFinish(this.orderId).then((res) => {
              if (res.code == 200) {
                this.successTips()
              } else {
                this.$refs.uToast.show({
                  title: res.data,
                  type: 'error',
                })
              }
            })
          } else {
            this.$u.api
              .outOrderFinish({ customerPayType: 'CASH' }, this.orderId)
              .then((res) => {
                if (res.code == 200) {
                  this.successTips()
                } else {
                  this.$refs.uToast.show({
                    title: res.data,
                    type: 'error',
                  })
                }
              })
          }
        } else {
          this.$refs.uToast.show({
            title: res.message,
            type: 'error',
          })
        }
      })
    },
    // 提交成功后续
    successTips() {
      uni.showModal({
        title: '提交成功',
        content: '是否查看本单服务质量详情？',
        confirmText: '好的',
        cancelText: '算了',
        success: res => {
          if (res.confirm) {
            uni.reLaunch({
              url: `/pages/order/quality?id=${this.orderId}`,
            })
          } else if (res.cancel) {
            if (this.completeBack) {
              // 从订单管理和浏览记录进来
              uni.navigateBack({
                delta: this.completeBack,
              })
            } else {
              uni.reLaunch({
                url: '/pages/index/order?type=audit',
              })
            }
          }
        }
      })
    },
    calMaterialCraftListAmount(arr) {
      let amount = 0
      if (arr) {
        arr.forEach((item) => {
          let useLength =
            (item.hasOwnProperty('useLength') && Number(item.useLength)) || 0
          let freeLength =
            (item.hasOwnProperty('freeLength') && Number(item.freeLength)) || 0
          let unitAmt =
            (item.hasOwnProperty('unitAmt') && Number(item.unitAmt)) || 0
          amount += Math.max(useLength - freeLength, 0) * unitAmt
          if (item.hasOwnProperty('extraAmt') && Number(item.extraAmt)) {
            amount += Number(item.extraAmt)
          }
        })
      }
      return amount
    },

    setData(data) {
      // 通过页面设置数据
      Object.keys(data).forEach((key) => {
        this.$set(this.form, key, data[key])
      })
      // 更新预计超出金额
      let amount = 0
      amount += this.calMaterialCraftListAmount(this.form.materialList)
      amount += this.calMaterialCraftListAmount(this.form.craftList)
      this.$set(this.form, 'overAmount', amount || 0)
    },
    // 字段的值更新
    fieldValueChange(data) {
      const groupItem = this.list[this.tabIndex].items[data.groupIndex]
      let innerItem
      if (groupItem.items) {
        innerItem = groupItem.items[data.itemIndex]
      }

      if (innerItem.fieldsType === 'multiInput') {
        // 多个输入框的值触发
        let key = Object.keys(data.value)[0]
        this.form[key] = data.value[key]
      } else {
        if (innerItem.fieldsName === 'orderSpareParts' && data.value === '[]') {
          this.$set(this.form, innerItem.fieldsName, '')
        } else {
          this.$set(this.form, innerItem.fieldsName, data.value)
        }
      }

      // 根据选择的值隐藏对应的项
      if (fields[innerItem.fieldsName]) { 
        groupItem.items.forEach(c => {
          if (fields[innerItem.fieldsName]['fieldsName'].includes(c.fieldsName)) { 
              c.required = data.value !== fields[innerItem.fieldsName]['value']
          }
        })
      }

      if (
        innerItem.fieldsName === 'pipe' ||
        innerItem.fieldsName === 'pipeUseLength'
      ) {
        // 申请费用计算
        this.calcMoney()
      }
      // console.log("this.form", this.form)
    },
    // 申请费用计算
    calcMoney() {
      const price = parseInt(this.form.pipe) || 0
      const pipeUseLength = parseFloat(this.form.pipeUseLength) || 0
      if (price && pipeUseLength) {
        const money = (price * pipeUseLength).toFixed(2)
        this.$set(this.form, 'pipeAmount', money)
      } else {
        this.$set(this.form, 'pipeAmount', 0)
      }
    },
    // ------------------------- 以下方法为上传组件相关 -------------------------
    // 弹出上传选项
    selectUpload(item, groupIndex, itemIndex) {
      const imgList = this.$refs[`fileChild${groupIndex}${itemIndex}`][0]
        .imgList
      if (imgList.length === 10) {
        return this.$refs.uToast.show({
          title: '图片已超出最大数量',
          type: 'error',
        })
      }
      this.photoItem = {
        ...JSON.parse(item),
        groupIndex,
        itemIndex,
      }
      // 弹窗展示
      this.maskShow = true
    },
    // 区分上传动作
    uploadSelect(index) {
      if (index === 0) {
        this.uploadFile('photo')
      } else {
        this.uploadFile()
      }
    },
    // 拍照回调
    async closeTake(val) {
      if (val && val.length > 0) {
        const order = {
          orderNumber: this.orderNumber,
          fieldsName: this.photoItem.fieldsName,
          fieldsTitle: this.photoItem.fieldsTitle,
          uploadType: 'camera',
        }
        const value = await this.saveToTask(val, order)
        this.$refs[
          `fileChild${this.photoItem.groupIndex}${this.photoItem.itemIndex}`
        ][0].setTmpValue(value)
      }
      this.takeStatus = false
    },
    // 上传图片
    async uploadFile(type) {
      const self = this
      if (type && type === 'photo') {
        // 直接打开相册
        let options = {
          sourceType: ['album'], //['album', 'camera']
          count: 3,
          sizeType: ['original'],
        }
        const order = {
          orderNumber: this.orderNumber,
          fieldsName: this.photoItem.fieldsName,
          fieldsTitle: this.photoItem.fieldsTitle,
          uploadType: 'album',
        }
        const value = await this.chooseImg(options, order)
        self.$refs[
          `fileChild${self.photoItem.groupIndex}${self.photoItem.itemIndex}`
        ][0].setTmpValue(value)
        return
      }
      // 使用拍照工具拍摄
      this.photograph()
      this.getWatermark()
    },
    // 获取拍照规范
    photograph() {
      let self = this
      let param = {
        partnerCompanyId: this.partnerCompanyId || '',
        categoryId: this.categoryId,
        brandId: this.brandId || '',
        fieldName: this.photoItem.fieldsName,
      }
      this.$u.api.orderStandardItem(param).then((res) => {
        if (res.code == 200 && res.data.length > 0) {
          self.currentItemDate = res.data[0]
        } else {
          console.log('获取完工项的拍照标准异常', res.data.message)
        }
        self.takeStatus = true
      })
    },
    // 获取水印
    getWatermark() {
      if (getApp().globalData.photo.waterSetting) {
        return
      }
      var data = { partnerCompanyId: this.partnerCompanyId || '' }
      this.$u.api.getWatermark(data).then((res) => {
        if (res.code == 200) {
          getApp().globalData.photo.waterSetting = res.data
        } else {
          console.log('获取水印备注异常', res.data.message)
        }
      })
    },
    // ------------------------- 以上方法为上传组件相关 -------------------------

    // ------------------------- 以下方法为展示滚动切换 -------------------------
    // 点击左边的栏目切换
    async swichMenu(index) {
      if (this.arr.length == 0) {
        await this.getMenuItemTop()
      }
      // if (index == this.current) return;
      this.scrollRightTop = this.oldScrollTop
      this.$nextTick(function() {
        setTimeout(() => {
          // 没有指定滚动到某一小项，就滚动到大的项
          this.scrollRightTop = this.arr[index]
          this.current = index
        }, 100)
      })
    },
    // 获取右边菜单每个item到顶部的距离
    getMenuItemTop() {
      new Promise((resolve) => {
        let selectorQuery = uni.createSelectorQuery()
        selectorQuery
          .selectAll('.class-item')
          .boundingClientRect((rects) => {
            // 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
            if (!rects.length) {
              setTimeout(() => {
                this.getMenuItemTop()
              }, 10)
              return
            }
            rects.forEach((rect) => {
              // 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
              this.arr.push(rect.top - rects[0].top)
              resolve()
            })
          })
          .exec()
      })
    },
    // 右边菜单滚动
    async rightScroll(e) {
      this.oldScrollTop = e.detail.scrollTop
      if (this.arr.length == 0) {
        await this.getMenuItemTop()
      }
      if (this.timer) return
      this.timer = setTimeout(() => {
        // 节流
        this.timer = null
        // scrollHeight为右边菜单垂直中点位置
        let scrollHeight = e.detail.scrollTop
        for (let i = 0; i < this.arr.length; i++) {
          let height1 = this.arr[i]
          let height2 = this.arr[i + 1]
          // 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
          if (!height2 || (scrollHeight >= height1 && scrollHeight < height2)) {
            this.current = i
            return
          }
        }
      }, 100)
    },
    handleTouchstart() {
      // 防止输入光标滚动出现错乱
      uni.hideKeyboard()
    },
    // 返回上一页更新订单状态
    backGo() {
      // const pages = getCurrentPages()
      // const beforePage = pages[pages.length - 2]
      // if (beforePage.$vm.loadOrderDetail) beforePage.$vm.loadOrderDetail()
      uni.navigateBack()
    },
  },
}
</script>

<style lang="scss" scoped>
// ----------------------------  表单样式begin  ----------------------------
/deep/ .u-form-item {
  .u-form-item__message {
    padding-left: 0 !important;
  }

  .u-form-item--left__content--required {
    vertical-align: top;
  }
}

.class-item {
  background-color: #fff;
  padding: 28rpx;
  border-radius: 8rpx;
  .title {
    font-weight: bold;
    font-size: 32rpx;
    line-height: 32rpx;
    color: #333;
  }
  .label {
    color: #333;
    font-size: 28rpx;
    line-height: 40rpx;
    padding-bottom: 20rpx;
  }
  .label-bold {
    font-size: 32rpx;
    font-weight: bold;
  }
  .required {
    padding-right: 10rpx;
    font-size: 28rpx;
    line-height: 40rpx;
    color: #fa3534;
  }

  .item-image {
    width: 24rpx;
    height: 24rpx;
    margin-right: 10rpx;
  }
}

// ----------------------------  表单样式end  ----------------------------

.com-content {
  height: calc(100vh);
  /* #ifdef H5 */
  height: calc(100vh - var(--window-top));
  /* #endif */
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  background-image: linear-gradient(to top, #2272ff 0%, #2272ff 100%);
  background-size: 750rpx 600rpx;
  background-repeat: no-repeat;
}

.u-search-box {
  padding: 18rpx 30rpx;
}

.order-tabs {
  margin-top: 20rpx;
  margin-bottom: 32rpx;
}

.u-menu-wrap {
  // flex: 1;
  height: 100%;
  overflow: auto;
  // overflow: hidden;
  border-radius: 12rpx 12rpx 0 0;
}

.detail-view {
  border-radius: 12rpx;
  margin: 30rpx;
}

.u-search-inner {
  background-color: rgb(234, 234, 234);
  border-radius: 100rpx;
  display: flex;
  align-items: center;
  padding: 10rpx 16rpx;
}

.u-search-text {
  font-size: 26rpx;
  color: $u-tips-color;
  margin-left: 10rpx;
}

.u-tab-view {
  width: 200rpx;
  height: 100%;
  border: 4rpx solid #f4f5f7;
  overflow: auto;
}

.u-tab-item {
  height: 110rpx;
  background: #fff;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
  color: #333333;
  font-weight: 400;
  line-height: 1;
}

.u-tab-item-active {
  position: relative;
  color: #2272ff;
  background: #fff;
}

// .u-tab-item-active::before {
//  content: "";
//  position: absolute;
//  border-left: 4px solid $u-type-primary;
//  height: 32rpx;
//  left: 0;
//  top: 39rpx;
// }

.u-tab-view {
  height: 100%;
}

.right-box,
.right-boxs {
  // background-color: rgb(250, 250, 250);
  background-color: #ffffff;
  overflow: auto;
  width: 100%;
}

.page-view {
  padding: 16rpx;
}

.class-item:last-child {
  max-height: 100vh;
}

.item-title {
  font-size: 26rpx;
  color: $u-main-color;
  font-weight: bold;
}

.item-menu-name {
  font-weight: normal;
  font-size: 24rpx;
  color: $u-main-color;
}

.item-container {
  display: flex;
  flex-wrap: wrap;
}

.thumb-box {
  width: 33.333333%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  margin-top: 20rpx;
}

.item-menu-image {
  width: 120rpx;
  height: 120rpx;
}

/*提交按钮*/
.btn-bottom {
  border: 2rpx solid #f4f5f7;
}

.btn-wrap {
  width: 100%;
  padding: 20rpx 0 44rpx 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.read-only {
  justify-content: flex-end;
  padding-right: 30rpx;
}

.btn-save {
  color: #ffffff;
  background-color: #2272ff;
  font-size: 32rpx;
  font-weight: bold;
}
.img-list {
  position: relative;
  margin: 8rpx;
  width: 160rpx;
  height: 160rpx;

  .pic {
    // margin-right: 15rpx;
    // margin-bottom: 15rpx;
    &:nth-child(3n) {
      margin-right: 0;
    }
  }
}
</style>
