<template>
  <view class="all-container">
    <view class="bg"></view>
    <zj-page-layout
      :isScroll="true"
      :hasFooter="true"
      :refresherTriggered="refresherTriggered"
      @refresherrefresh="refresherrefresh"
    >
      <!-- 状态 -->
      <view class="status-container">
        <view class="status" @tap="openFeedback"
          >{{ detail ? detail.orderStatusText : '' }}<text class="iconfont icon-jinru"></text
        ></view>
        <view class="time" v-if="detail && detail.appointmentTime"
          >已预约 {{ detail.appointmentTime.slice(0, 10) }}</view
        >
      </view>

      <!-- tab栏 -->
      <view class="tab-container">
        <u-tabs :scrollable="true" :list="tabList" :current="curTab - 1" @click="changeTab" itemStyle="height: 36px;">
        </u-tabs>
      </view>

      <view class="content-container" v-if="detail">
        <!-- 基本信息 -->
        <block v-if="~[1].indexOf(curTab)">
          <view class="user-container card">
            <view class="top">
              <view class="type">
                <view class="left">{{ detail.orderSmallTypeText ? detail.orderSmallTypeText.slice(0, 2) : '' }}</view>
                <view v-if="detail && orderStatus_v !== 'DQD'" class="right" @tap="copyData()">复制</view>
              </view>
              <view class="user">{{ detail.userName }} {{ detail.userMobile }}</view>
              <view class="address">
                <view class="text"
                  >{{ detail.province }}{{ detail.city }}{{ detail.area }}{{ detail.street
                  }}{{ detail.address || detail.gpsAddress }}
                </view>
                <view
                  v-if="detail && orderStatus_v !== 'DQD'"
                  class="ctrl"
                  @tap.stop="
                    $openLocation({
                      lat: detail.lat,
                      lng: detail.lng,
                      address: detail.address || detail.gpsAddress
                    })
                  "
                  ><text class="iconfont icon-daohang"></text>导航</view
                >
              </view>
            </view>
            <view class="bottom" v-if="detail && orderStatus_v !== 'DQD'">
              <view class="it" @tap="$callPhone(detail.userMobile)"
                ><text class="iconfont icon-call"></text>联系电话1</view
              >
              <view class="it" @tap="$callPhone(detail.userMobile2 || detail.userMobile)"
                ><text class="iconfont icon-call"></text>联系电话2</view
              >
            </view>
          </view>

          <!-- 商品信息 -->
          <view class="goods-container card mt30">
            <view class="common-title">商品信息</view>
            <view class="item" v-for="(item, index) in detail.pgOrderProducts" :key="index">
              <view class="main">
                <image :src="item.imgUrl ? item.imgUrl : require('@/static/images/logo.png')" mode="aspectFill"></image>
                <view class="info">
                  <view class="name">
                    <view class="left" v-if="detail.isZl">{{ item.mainName || '' }}</view>
                    <view class="left" v-else>{{ item.smallName || '' }} {{ item.productName || '' }}</view>
                    <view class="right">x{{ item.num }}</view>
                  </view>
                  <view class="tags" v-if="!detail.isZl">
                    <view class="it">{{ item.brandName }}</view>
                    <!-- <view class="it">家用空调</view> -->
                  </view>
                </view>
              </view>
              <!-- <view class="images" v-if="isOpenGoods">
          			<view class="it" v-if="item.insideImg">
          				<image :src="imageUrl + item.insideImg" mode="aspectFill"
          					@tap="prevImg(item.insideImg)"></image>
          				<view class="text">内机</view>
          			</view>
          			<view class="it" v-if="item.outImg">
          				<image :src="imageUrl + item.outImg" mode="aspectFill" @tap="prevImg(item.outImg)">
          				</image>
          				<view class="text">外机</view>
          			</view>
          			<block v-if="item.partImgs">
          				<view class="it" v-for="(it, idx) in item.partImgs.split(',')" :key="idx">
          					<image :src="imageUrl + it" mode="aspectFill" @tap="() => prevImg(it)"></image>
          					<view class="text">配件</view>
          				</view>
          			</block>
          		</view> -->
            </view>
            <!-- <view class="ctrl" @tap="isOpenGoods = !isOpenGoods">
          		<text>{{ isOpenGoods ? '收起' : '查看更多' }}</text>
          		<text class="iconfont icon-left" :class="isOpenGoods ? 'is' : ''"></text>
          	</view> -->
          </view>

          <!-- 订单信息 -->
          <view class="info-container card mt30" v-if="detail.saleOrderId && !detail.pgIncreId">
            <view class="common-title">订单信息</view>
            <view>
              <view class="row">
                <view class="label">订单编号</view>
                <view class="value">{{ detail.saleOrderId }}</view>
                <view v-if="detail && orderStatus_v !== 'DQD'" class="ctrl" @tap="$copy(detail.saleOrderId)">复制</view>
              </view>
              <view class="row">
                <view class="label">下单时间</view>
                <view class="value">{{ detail.saleCreateTime || '' }}</view>
              </view>
              <view class="row">
                <view class="label">订单金额</view>
                <view class="value">¥{{ detail.saleTotalAmount | priceFilter }}</view>
              </view>
              <view class="row">
                <view class="label">订单备注</view>
                <view class="value">{{ detail.saleRemark || '' }}</view>
              </view>
            </view>
          </view>

          <view class="info-container card mt30" v-if="detail.pgIncreId && increDetail">
            <view class="common-title">产品信息</view>
            <view class="row">
              <view class="label">服务类型</view>
              <view class="value">延保</view>
            </view>
            <view class="row">
              <view class="label">产品品牌</view>
              <view class="value">{{ increDetail.brandName }}</view>
            </view>
            <view class="row">
              <view class="label">产品大类</view>
              <view class="value">{{ increDetail.mainName }}</view>
            </view>
            <view class="row">
              <view class="label">服务内容</view>
              <view class="value">{{ increDetail.increContent }}</view>
            </view>
          </view>

          <view class="info-container card mt30" v-if="detail.pgIncreId && increDetail">
            <view class="common-title">产品凭证</view>
            <view class="row">
              <view class="label">内机条码</view>
              <view class="value">{{ increDetail.insideCode }}</view>
            </view>
            <view class="imgs">
              <!-- 内机条码 -->
              <view class="it">
                <block>
                  <image mode="aspectFill" :src="increDetail.insideCodeImg" @tap="prevImg(increDetail.insideCodeImg)">
                  </image>
                </block>
                <view class="name">内机条码</view>
              </view>
              <!-- 机器铭牌 -->
              <view class="it">
                <block>
                  <image mode="aspectFill" :src="increDetail.machineImg" @tap="prevImg(increDetail.machineImg)">
                  </image>
                </block>
                <view class="name">机器铭牌<br />(含出厂日期)</view>
              </view>
              <!-- 购机凭证 -->
              <view class="it">
                <block>
                  <image mode="aspectFill" :src="increDetail.buyCertImg" @tap="prevImg(increDetail.buyCertImg)">
                  </image>
                </block>
                <view class="name">购机凭证</view>
              </view>
            </view>
          </view>

          <!-- 延保订单信息 -->
          <view class="info-container card mt30" v-if="detail.pgIncreId && increDetail">
            <view class="common-title">订单信息</view>
            <view>
              <view class="row">
                <view class="label">订单编号</view>
                <view class="value">{{ increDetail.id }}</view>
                <view v-if="detail && orderStatus_v !== 'DQD'" class="ctrl" @tap="$copy(increDetail.id)">复制</view>
              </view>
              <view class="row">
                <view class="label">下单时间</view>
                <view class="value">{{ increDetail.createTime || '' }}</view>
              </view>
              <view class="row">
                <view class="label">订单金额</view>
                <view class="value">¥{{ increDetail.amount }}</view>
              </view>
              <view class="row">
                <view class="label">订单备注</view>
                <view class="value">{{ detail.remark || '' }}</view>
              </view>
            </view>
          </view>

          <!-- 服务信息 -->
          <view class="info-container card mt30">
            <view class="common-title">服务信息</view>
            <view>
              <view class="row">
                <view class="label">工单编号</view>
                <view class="value">{{ detail.id }}</view>
                <view v-if="detail && orderStatus_v !== 'DQD'" class="ctrl" @tap="$copy(detail.id)">复制</view>
              </view>
              <view class="row">
                <view class="label">下单时间</view>
                <view class="value">{{ detail.createTime }}</view>
              </view>
              <view class="row">
                <view class="label">接单时间</view>
                <view class="value">{{ detail.workerReceTime || '' }}</view>
              </view>
              <view class="row">
                <view class="label">主工程师</view>
                <view class="value">{{ detail.workerName }} {{ detail.workerMobile }}</view>
                <view v-if="detail && orderStatus_v !== 'DQD'" class="ctrl" @tap="$callPhone(detail.workerMobile)"
                  ><text class="iconfont icon-call"></text
                ></view>
              </view>
              <view class="row" v-for="(item, index) in detail.pgOrderWorkers.filter(o => !o.isMaster)" :key="index">
                <view class="label">辅工程师</view>
                <view class="value">{{ item.workerName }} {{ item.workerMobile }}</view>
                <view v-if="detail && orderStatus_v !== 'DQD'" class="ctrl" @tap="$callPhone(item.workerMobile)"
                  ><text class="iconfont icon-call"></text
                ></view>
              </view>
              <view class="row">
                <view class="label">下单渠道</view>
                <view class="value">{{ detail.orderChannelText || '' }}</view>
              </view>
              <view class="row">
                <view class="label">订单备注</view>
                <view class="value">{{ detail.remark || '' }}</view>
              </view>
            </view>
          </view>

          <!-- 建单信息 -->
          <view class="info-container card mt30">
            <view class="common-title">建单信息</view>
            <view>
              <view class="row">
                <view class="label">建单人名</view>
                <view class="value">{{ detail.createBy || '' }}</view>
              </view>
              <view class="row">
                <view class="label">下单网点</view>
                <view class="value">{{ detail.websitName || '' }}</view>
              </view>
            </view>
          </view>
        </block>

        <!-- 服务信息 -->
        <block v-if="~[2].indexOf(curTab)">
          <!-- 过程反馈 -->
          <view class="feedback-container card">
            <view class="common-title2">
              <view class="title">过程反馈</view>
              <view v-if="detail && orderStatus_v !== 'DQD'" class="right" @tap="toFeedbackList"
                >查看全部<text class="iconfont icon-jinru"></text>
              </view>
            </view>
            <view class="list" v-if="detail.lastOperator">
              <view class="item">
                <u-avatar
                  :text="detail.lastOperatorWebsit ? detail.lastOperatorWebsit.slice(0, 1) : 'A'"
                  fontSize="18"
                  randomBgColor
                ></u-avatar>
                <view class="main">
                  <view class="name">{{ detail.lastOperatorWebsit || '' }}</view>
                  <view class="time">{{ detail.lastOperatorTime || '' }}</view>
                  <view class="content">{{ detail.lastOperator || '' }}</view>
                </view>
              </view>
            </view>
            <Loading :type="3" :loadStatus="2" :isLoadAnimation="false" v-else />
          </view>

          <!-- 预约信息 -->
          <view class="info-container card mt30" v-if="detail && detail.appointmentTime">
            <view class="common-title">预约信息</view>
            <view>
              <view class="row">
                <view class="label">预约时间</view>
                <view class="value">{{ detail.appointmentTime.slice(0, 10) }}</view>
              </view>
              <view class="row">
                <view class="label">预约备注</view>
                <view class="value">{{ detail.changeRemark || detail.appointmentRemark }}</view>
              </view>
            </view>
          </view>

          <!-- 完工信息 -->
          <view class="info-container card mt30" v-if="detail && (orderStatus_v == 'YWG' || orderStatus_v == 'YJS')">
            <view class="common-title2">
              <view class="title">完工信息</view>
              <view v-if="detail && orderStatus_v !== 'DQD'" class="right" @tap="toOverDetail"
                >查看更多<text class="iconfont icon-jinru"></text
              ></view>
            </view>
            <view>
              <view class="row">
                <view class="label">完工时间</view>
                <view class="value">{{ detail.overTime || detail.websitOverTime || '' }}</view>
              </view>
              <view class="row">
                <view class="label">完工地点</view>
                <view class="value"
                  >{{ detail.province }}{{ detail.city }}{{ detail.area }}{{ detail.street }}{{ detail.address }}
                </view>
              </view>
            </view>
          </view>
        </block>

        <!-- 电子支付 -->
        <block v-if="~[3].indexOf(curTab)">
          <block v-if="detail.rpProjectRepairId">
            <view class="product-container card" v-for="(item, index) in payList" :key="index">
              <view class="row">
                <view class="label">支付单号</view>
                <view class="value">{{ item.orderId }}</view>
              </view>
              <view class="row">
                <view class="label">支付状态</view>
                <view class="value" style="color: red">{{ item.examineStatus | examineStatusFilter }}</view>
              </view>
              <view class="common-title mt30">产品信息</view>
              <view class="product">
                <view
                  class="it"
                  v-for="(it, idx) in item.rpMaterialOrderItems.filter(
                    o => o.chargeType == 'ACC' || o.chargeType == 'MCC'
                  )"
                  :key="idx"
                >
                  <view class="name"
                    >{{ it.goodsName }}<text>×{{ it.num }}</text></view
                  >
                  <view class="price">¥{{ it.totalAmount }}</view>
                </view>
                <view class="total">
                  <view class="text">合计：</view>
                  <view class="price"
                    >¥{{
                      [
                        0,
                        0,
                        0,
                        ...item.rpMaterialOrderItems
                          .filter(o => o.chargeType == 'ACC' || o.chargeType == 'MCC')
                          .map(val => val.totalAmount)
                      ].reduce((a, b) => (a * 100 + b * 100) / 100, 0)
                    }}</view
                  >
                </view>
              </view>
              <view class="common-title mt30">服务费用</view>
              <view class="product">
                <view
                  class="it"
                  v-for="(it, idx) in item.rpMaterialOrderItems.filter(o => o.chargeType == 'SERV')"
                  :key="idx"
                >
                  <view class="name">{{ it.amountName }}</view>
                  <view class="price">¥{{ it.normAmount }}</view>
                </view>
                <view class="total">
                  <view class="text">合计：</view>
                  <view class="price"
                    >¥{{
                      [
                        0,
                        0,
                        0,
                        ...item.rpMaterialOrderItems.filter(o => o.chargeType == 'SERV').map(val => val.normAmount)
                      ].reduce((a, b) => (a * 100 + b * 100) / 100, 0)
                    }}</view
                  >
                </view>
              </view>
              <view class="bottom">
                <view class="left">订单总金额</view>
                <view class="right">
                  <view class="text">合计：</view>
                  <view class="price"
                    >¥{{
                      [
                        0,
                        0,
                        0,
                        ...item.rpMaterialOrderItems.filter(o => o.chargeType == 'SERV').map(val => val.normAmount),
                        ...item.rpMaterialOrderItems
                          .filter(o => o.chargeType == 'ACC' || o.chargeType == 'MCC')
                          .map(val => val.totalAmount)
                      ].reduce((a, b) => (a * 100 + b * 100) / 100, 0)
                    }}</view
                  >
                </view>
              </view>
              <view class="row mt30">
                <view class="label">操作人员</view>
                <view class="value">{{ item.createBy }}</view>
              </view>
              <view class="row mt20">
                <view class="label">订单备注</view>
                <view class="value">{{ item.remark }}</view>
              </view>
            </view>
          </block>
          <block v-else>
            <view class="product-container card" v-for="(item, index) in payList" :key="index">
              <view class="common-title mt30">支付费用{{ index + 1 }}</view>
              <view class="row">
                <view class="label">支付单号</view>
                <view class="value">{{ item.orderId }}</view>
              </view>
              <view class="row">
                <view class="label">支付状态</view>
                <view
                  class="value"
                  :style="{ color: item.payStatus == 'WAIT' ? 'red' : item.payStatus == 'PAID' ? 'blue' : '' }"
                  >{{ item.payStatus | payStatusFilter }}</view
                >
              </view>
              <view class="common-title mt30">产品信息</view>
              <view class="product">
                <view
                  class="it"
                  v-for="(it, idx) in item.workerOrderItems.filter(o => o.chargeType == 'ACC' || o.chargeType == 'MCC')"
                  :key="idx"
                >
                  <view class="name"
                    >{{ it.goodsName }}<text>×{{ it.num }}</text></view
                  >
                  <view class="price">¥{{ it.totalAmount }}</view>
                </view>
                <view class="total">
                  <view class="text">合计：</view>
                  <view class="price"
                    >¥{{
                      [
                        0,
                        0,
                        0,
                        ...item.workerOrderItems
                          .filter(o => o.chargeType == 'ACC' || o.chargeType == 'MCC')
                          .map(val => val.totalAmount)
                      ].reduce((a, b) => (a * 100 + b * 100) / 100, 0)
                    }}</view
                  >
                </view>
              </view>
              <view class="common-title mt30">服务费用</view>
              <view class="product">
                <view
                  class="it"
                  v-for="(it, idx) in item.workerOrderItems.filter(o => o.chargeType == 'SERV')"
                  :key="idx"
                >
                  <view class="name">{{ it.amountName }}</view>
                  <view class="price">¥{{ it.normAmount }}</view>
                </view>
                <view class="total">
                  <view class="text">合计：</view>
                  <view class="price"
                    >¥{{
                      [
                        0,
                        0,
                        0,
                        ...item.workerOrderItems.filter(o => o.chargeType == 'SERV').map(val => val.normAmount)
                      ].reduce((a, b) => (a * 100 + b * 100) / 100, 0)
                    }}</view
                  >
                </view>
              </view>
              <view class="bottom">
                <view class="left">订单总金额</view>
                <view class="right">
                  <view class="text">合计：</view>
                  <view class="price"
                    >¥{{
                      [
                        0,
                        0,
                        0,
                        ...item.workerOrderItems.filter(o => o.chargeType == 'SERV').map(val => val.normAmount),
                        ...item.workerOrderItems
                          .filter(o => o.chargeType == 'ACC' || o.chargeType == 'MCC')
                          .map(val => val.totalAmount)
                      ].reduce((a, b) => (a * 100 + b * 100) / 100, 0)
                    }}</view
                  >
                </view>
              </view>
              <view class="row mt30">
                <view class="label">操作人员</view>
                <view class="value">{{ item.createBy }}</view>
              </view>
              <view class="row mt20">
                <view class="label">订单备注</view>
                <view class="value">{{ item.remark }}</view>
              </view>
              <view style="height: 20rpx"></view>
              <view v-if="item.payStatus == 'WAIT'">
                <u-button type="success" text="扫码支付" @click="scanCode(item)">扫码支付</u-button>
              </view>
            </view>
          </block>

          <block v-if="payList.length < 1">
            <Loading :type="3" :loadStatus="2" showText="暂无电子支付信息" :isLoadAnimation="false" />
          </block>
        </block>

        <!-- 费用结算 -->
        <block v-if="~[4].indexOf(curTab)">
          <!-- 服务费用 -->
          <view class="info-container card mt30" v-for="(item, index) in settleList" :key="index">
            <block v-if="item.settleNormType !== 'OTHER'">
              <view class="common-title2">
                <view class="title">服务费用{{ index + 1 }}</view>
                <view class="right">{{ orderStatus_v == 'YJS' ? '已结算' : '结算中' }}</view>
              </view>
              <view>
                <view class="row">
                  <view class="label">产品大类</view>
                  <view class="value">{{ item.mainName || '' }}</view>
                </view>
                <view class="row">
                  <view class="label">产品小类</view>
                  <view class="value">{{ item.smallName || '' }}</view>
                </view>
                <view class="row">
                  <view class="label">机型名称</view>
                  <view class="value">{{ item.goodsName || '' }}</view>
                </view>
                <!-- <view class="row">
                  <view class="label">收费标准</view>
                  <view class="value">¥{{ item.normAmount | priceFilter }}</view>
                </view> -->
                <view class="row">
                  <view class="label">数&emsp;&emsp;量</view>
                  <view class="value">{{ item.settleNum || '' }}</view>
                </view>
                <view class="row">
                  <view class="label">结算金额</view>
                  <view class="value" v-if="orderStatus_v == 'YJS'">¥{{ item.workerSettleAmount | priceFilter }}</view>
                  <view class="value" v-else>-</view>
                </view>
              </view>
            </block>
            <block v-else>
              <view class="common-title2">
                <view class="title">其他费用</view>
                <view class="right">{{ orderStatus_v == 'YJS' ? '已结算' : '结算中' }}</view>
              </view>
              <view>
                <view class="row">
                  <view class="label">类&emsp;&emsp;型</view>
                  <view class="value">{{ item.typeName || '' }}</view>
                </view>
                <view class="row">
                  <view class="label">规&emsp;&emsp;格</view>
                  <view class="value">{{ item.label || '' }}</view>
                </view>
                <!-- <view class="row">
                  <view class="label">单&emsp;&emsp;价</view>
                  <view class="value">¥{{ item.normAmount | priceFilter }}</view>
                </view> -->
                <view class="row">
                  <view class="label">数&emsp;&emsp;量</view>
                  <view class="value">{{ item.settleNum || '' }}</view>
                </view>
                <view class="row">
                  <view class="label">结算金额</view>
                  <view class="value" v-if="orderStatus_v == 'YJS'">¥{{ item.workerSettleAmount | priceFilter }}</view>
                  <view class="value" v-else>-</view>
                </view>
              </view>
            </block>
          </view>
          <block v-if="settleList.length < 1">
            <Loading :type="3" :loadStatus="2" showText="暂无员工结算信息" :isLoadAnimation="false" />
          </block>
        </block>
      </view>

      <Loading :type="3" :loadStatus="loadStatus" :isLoadAnimation="false" />

      <template slot="footer">
        <view class="bottom-container" v-if="detail">
          <!-- 待抢单 -->
          <block v-if="orderStatus_v == 'DQD' && (detail.orderType == 'INSTALL' ? !!userInfo.workerNumber : true)">
            <u-button type="primary" text="抢单" @tap="qdOrder(detail)"></u-button>
          </block>
          <u-button
            v-if="
              ((orderStatus_v == 'DJD' && !detail.isImportExcel) || (detail.isImportExcel && !detail.isMeet)) &&
              (detail.orderType == 'INSTALL' ? !!userInfo.workerNumber : true)
            "
            type="primary"
            text="接单"
            @tap="actionReceive()"
          ></u-button>
          <!-- 待接单 -->
          <block v-if="orderStatus_v == 'DJD'">
            <u-button
              plain
              type="primary"
              text="配件申请"
              v-if="detail.orderType != 'INSTALL'"
              @tap="toPartsApply()"
            ></u-button>
            <u-button
              plain
              type="primary"
              text="取消加急"
              @tap="actionUrgent(false)"
              v-if="detail.pgOrderFlags && detail.pgOrderFlags.some(o => o.tag == 'JIA_JI')"
            ></u-button>
            <u-button plain type="primary" text="加急" @tap="actionUrgent(true)" v-else></u-button>
          </block>
          <!-- 服务中 -->
          <block v-if="orderStatus_v == 'FWZ' || orderStatus_v == 'YCD'">
            <u-button
              v-if="userInfo.workerNumber == detail.workerNumber"
              plain
              type="primary"
              text="变更小工"
              @tap="biangengxiaogong()"
            ></u-button>
            <u-button
              plain
              type="primary"
              text="配件申请"
              v-if="detail.orderType != 'INSTALL'"
              @tap="toPartsApply()"
            ></u-button>
            <u-button
              plain
              type="primary"
              text="辅材收费"
              @tap="toCharge('M')"
              v-if="detail.orderType == 'INSTALL'"
            ></u-button>
            <u-button plain type="primary" text="配件收费" @tap="toCharge('P')" v-else></u-button>
            <u-button type="primary" text="过程反馈" @tap="toFeedback()"></u-button>
          </block>
        </view>
      </template>
    </zj-page-layout>
    <selectionWorkers
      v-if="item"
      :title="title"
      :detail="item"
      :type="selectionWorkersType"
      :callback="callback"
      @close="
        () => {
          item = null
          selectionWorkersType = null
          callback = null
        }
      "
    />
    <u-popup :show="isShowFeedback" @close="isShowFeedback = false" closeable round="10">
      <view class="feedback-dialog">
        <view class="title">服务路由</view>
        <view class="content">
          <logistics :logisticsData="feedbackList"></logistics>
        </view>
      </view>
    </u-popup>

    <zhifutanchuan
      v-if="state > 0"
      :detail="detail_zf"
      :orderId="orderId_zf"
      :state="state"
      @scan="scan"
      @back="back"
      @offTiming="offTiming"
    />
  </view>
</template>

<script>
import zjDialogPicker from '@/components/zj-dialog/zj-dialog-picker.vue'
import Logistics from '@/components/logistics2/common-logistics.vue'
import selectionWorkers from '@/components/selectionWorkers.vue'
import zhifutanchuan from '@/components/zhifutanchuan.vue'
import { wxScanCode } from '@/common/utils/util.js'
import { getStorage } from '@/common/utils/storage.js'
export default {
  components: {
    zjDialogPicker,
    Logistics,
    selectionWorkers,
    zhifutanchuan
  },

  filters: {
    payStatusFilter(val) {
      const MAP = {
        CANCEL: '已取消',
        WAIT: '待支付',
        PAID: '已支付'
      }
      return MAP[val]
    },
    examineStatusFilter(val) {
      const MAP = {
        WAIT: '待审批',
        OK: '审批通过',
        FAIL: '审批驳回',
        NO: '已取消',
        PAID: '已现场支付',
        NO_PAID: '未支付'
      }
      return MAP[val]
    }
  },

  data() {
    return {
      id: null,
      imageUrl: this.$imageUrl,
      detail: null,
      increDetail: null,
      loadStatus: 1,
      errorText: '',
      refresherTriggered: false,
      curTab: 1,
      tabList: [
        { name: '基本信息', value: 1 },
        { name: '服务信息', value: 2 },
        { name: '电子支付', value: 3 },
        { name: '员工结算', value: 4 }
      ],
      isOpenGoods: false,

      payList: [], // 支付信息列表
      settleList: [], // 结算列表

      isShowFeedback: false,
      feedbackList: [],
      behavior: '',
      selectionWorkersType: '',
      item: null,
      callback: null,
      title: '',
      state: 0,
      detail_zf: null,
      orderId_zf: null
    }
  },

  computed: {
    userInfo() {
      return getStorage('user')
    },
    orderStatus_v() {
      if (['DYY'].includes(this?.detail?.orderStatus)) {
        // 待预约
        return 'DYY'
      } else if (['DQD'].includes(this?.detail?.orderStatus)) {
        // 待抢单
        return 'DQD'
      } else if (
        [
          'DSHPG',
          'CJ',
          'YPD',
          'DXSPD',
          'DZBPG',
          'DWDSPGP',
          'DXSSPGP',
          'DTJXSSPGP',
          'DZBSPGP',
          'DFZXPD',
          'DFZXSPGP',
          'XSBH',
          'TJXSBH',
          'ZBBH',
          'FZXBH',
          'FL'
        ].includes(this?.detail?.orderStatus)
      ) {
        // 待商户派工
        return 'DSHPG'
      } else if (['DWDPG', 'DWDPD', 'WDBH'].includes(this?.detail?.orderStatus)) {
        // 待网点派工
        return 'DWDPG'
      } else if (['DJD', 'DSM', 'YZP'].includes(this?.detail?.orderStatus)) {
        // 待接单
        return 'DJD'
      } else if (['FWZ', 'GCSZT', 'BFWG'].includes(this?.detail?.orderStatus)) {
        // 服务中
        return 'FWZ'
      } else if (['YCD'].includes(this?.detail?.orderStatus)) {
        // 异常单
        return 'YCD'
      } else if (['YWG', 'GCSZX', 'WDWG', 'YWGO'].includes(this?.detail?.orderStatus)) {
        // 已完工待结算
        return 'YWG'
      } else if (['YJS', 'LRCD'].includes(this?.detail?.orderStatus)) {
        // 已结算
        return 'YJS'
      } else if (['YQX', 'FWZT', 'YCGB', 'FWQX'].includes(this?.detail?.orderStatus)) {
        // 已取消
        return 'YQX'
      }
      return ''
    }
  },

  async onLoad({ id, behavior }) {
    this.id = id
    this.behavior = behavior
    await this.refreshData()
    this.crossPage.$on('refreshWorkorderDetail', async () => {
      await this.refreshData()
    })
  },

  onUnload() {
    this.crossPage.$off('refreshWorkorderDetail')
  },

  methods: {
    scan() {
      if (this.timeout) {
        clearTimeout(this.timeout)
      }
      this.scanCode()
    },

    back() {
      if (this.timeout) {
        clearTimeout(this.timeout)
      }
      this.$navToPage(
        {
          url: `/packageMaterial/pages/index?type=M`
        },
        'reLaunch'
      )
    },

    offTiming() {
      if (this.timeout) {
        clearTimeout(this.timeout)
      }
    },

    // 扫码
    async scanCode(item) {
      this.detail_zf = { ...item }
      this.orderId_zf = item.orderId
      var codeVal = await wxScanCode(['qrCode'])
      this.submitData(codeVal)
    },

    // 下单
    submitData(code) {
      this.$api
        .post('/pay/paid', {
          authCode: code,
          orderId: this.orderId_zf,
          payType: 'WECHAT'
        })
        .then(res => {
          if (res.data) {
            // 支付成功
            this.getPayList(() => {
              this.state = 2
            })
          } else {
            // 支付失败
            this.getPayList(() => {
              this.state = 4
            })
          }
        })
        .catch(res => {
          // 等待支付
          if (res.message === 'USERPAYING') {
            if (this.state == 0) {
              this.state = 1
            }
            this.getDetail__()
          } else {
            this.$tips(res.message)
          }
        })
    },

    getDetail__(cb) {
      this.$api
        .post('/pay/getOrder', {
          orderId: this.orderId_zf
        })
        .then(res => {
          this.detail_zf = res.data
          if (res.data.payStatus == 'PAID') {
            this.state = 2
          } else {
            this.timeout = setTimeout(() => {
              this.getDetail__(cb)
            }, 1000)
          }
          cb?.()
        })
        .catch(res => {})
        .finally(res => {})
    },

    // 触发下拉刷新
    async refresherrefresh(e) {
      this.refresherTriggered = true
      await this.refreshData()
    },

    async changeTab(e) {
      this.curTab = e.value
      this.loadStatus = 1
      await this.refreshData()
    },

    async refreshData() {
      try {
        await this.getDetail()
        await this.getSettleList()
        if (this.curTab === 1) {
          // await this.getDetail();
        } else if (this.curTab === 2) {
        } else if (this.curTab === 3) {
          await this.getPayList()
        } else if (this.curTab === 4) {
          await this.getSettleList()
        }
        this.refresherTriggered = false
        this.loadStatus = 0
      } catch (e) {
        this.loadStatus = 2
      }
    },

    // 获取详情
    getDetail() {
      return new Promise((resolve, reject) => {
        this.$api
          .post('/pg/order/base/detail', {
            orderBaseId: this.id
          })
          .then(res => {
            this.detail = res.data
            if (
              this.behavior === 'lqdd' &&
              !['DQD'].includes(res.data.orderStatus) &&
              res.data.workerId !== this.$store.state.user.userId
            ) {
              this.$modal({
                title: '提示',
                content: '来晚啦，工单已经被抢走了~',
                confirmText: '知道啦',
                showCancel: false
              })
                .then(() => {
                  uni.switchTab({
                    url: '/pages/index/index'
                  })
                })
                .catch(() => {
                  uni.switchTab({
                    url: '/pages/index/index'
                  })
                })
            }
            if (res.data.pgIncreOrderId) {
              this.getIncreDetail(res.data.pgIncreOrderId)
            }
            resolve(1)
          })
          .catch(res => {
            reject(0)
          })
      })
    },

    getIncreDetail(id) {
      this.$api
        .post('/increConfig/detailIncre', {
          id
        })
        .then(res => {
          this.increDetail = res.data
        })
    },

    copyData() {
      let name = this.detail.userName
      let phone = this.detail.userMobile
      let address = `${this.detail.gpsAddress ? this.detail.gpsAddress + this.detail.address : this.detail.address}`
      this.$copy(`${name}，${phone}，${address}`)
    },

    async openFeedback() {
      await this.getFeedbackList()
      this.isShowFeedback = true
    },

    getFeedbackList() {
      return new Promise((resolve, reject) => {
        this.$api
          .post('/pg/order/base/operator/list', {
            orderBaseId: this.id
          })
          .then(res => {
            let data = res.data.map(item => {
              return {
                title: item.type,
                time: item.createTime,
                content: item.content,
                imgSrc: item.imgSrc
              }
            })
            this.feedbackList = data
          })
          .finally(res => {
            resolve(1)
          })
      })
    },

    // 获取支付信息
    getPayList(cb) {
      return new Promise((resolve, reject) => {
        let url = ''
        if (this.detail.rpProjectRepairId) {
          url = '/engin/material/detailWorker'
        } else {
          url = '/changeOrder/getOrderList'
        }
        this.$api
          .post(url, {
            workerOrderId: this.id
          })
          .then(async res => {
            this.payList = res.data.map(item => {
              var gengduo = [
                {
                  chargeType: 'SERV',
                  amountName: '服务费用',
                  normAmount: item.servicePrice || 0
                },
                {
                  chargeType: 'SERV',
                  amountName: '其他费用',
                  normAmount: item.otherPrice || 0
                }
              ]
              if (this.detail.rpProjectRepairId) {
                if (!item.rpMaterialOrderItems) {
                  item.rpMaterialOrderItems = []
                }
                item.rpMaterialOrderItems.push(...gengduo)
              } else {
                if (!item.workerOrderItems) {
                  item.workerOrderItems = []
                }
                item.workerOrderItems.push(...gengduo)
              }
              return { ...item }
            })
            cb?.()
            resolve(1)
          })
          .catch(res => {
            cb?.()
            reject(0)
          })
      })
    },

    // 获取安装结算
    getSettleList() {
      return new Promise((resolve, reject) => {
        this.$api
          .post('/order/settle/norm/detail', {
            orderId: this.id
          })
          .then(res => {
            this.settleList = res.data
            if (this.settleList.length > 0 && this.orderStatus_v == 'YJS') {
              this.tabList[3].name = `员工结算(${this.settleList.reduce(
                (total, obj) => total + obj.workerSettleAmount,
                0
              )})`
            } else {
              this.tabList[3].name = `员工结算`
            }
            resolve(1)
          })
          .catch(res => {
            reject(0)
          })
      })
    },

    // 预览图片
    prevImg(url) {
      uni.previewImage({
        current: this.imageUrl + url,
        urls: [this.imageUrl + url]
      })
    },

    // 加急
    actionUrgent(flag) {
      this.$modal({
        title: '加急操作',
        content: '加急操作，会消息通知所有订单相关人员，请谨慎操作。'
      })
        .then(() => {
          this.$api
            .post('/pg/order/base/flag', {
              orderBaseId: this.id,
              orderFlagEnum: 'JIA_JI',
              flag: flag
            })
            .then(res => {
              this.$successToast()
              this.getDetail()
              this.crossPage.$emit('refreshWorkorderList', '')
            })
        })
        .catch(() => {})
    },

    // 变更小工
    biangengxiaogong() {
      this.title = '更换小工'
      this.selectionWorkersType = 3
      this.item = { ...this.detail }
      this.callback = () => {
        this.$successToast()
        this.getDetail()
        this.crossPage.$emit('refreshWorkorderList', '')
        this.$nextTick(() => {
          this.item = null
          this.selectionWorkersType = null
          this.callback = null
          this.title = null
        })
      }
    },

    // 接单
    actionReceive() {
      this.title = '接收确认'
      this.selectionWorkersType = 1
      this.item = { ...this.detail }
      this.callback = () => {
        this.$successToast()
        this.getDetail()
        this.crossPage.$emit('refreshWorkorderList', '')
        this.$nextTick(() => {
          this.item = null
          this.selectionWorkersType = null
          this.callback = null
          this.title = null
        })
      }
      // this.$modal({
      //   title: '接单确认',
      //   content: '确认接单？'
      // })
      //   .then(() => {
      //     this.$api
      //       .post('/pg/order/base/rece', {
      //         orderBaseId: this.id
      //       })
      //       .then(res => {
      //         this.$successToast()
      //         this.getDetail()
      //         this.crossPage.$emit('refreshWorkorderList', '')
      //       })
      //   })
      //   .catch(() => {})
    },

    qdOrder(item) {
      // this.title = '接收确认'
      // this.selectionWorkersType = 2
      // this.item = { ...item }
      // this.callback = () => {
      //   this.$successToast()
      //   this.getDetail()
      //   this.crossPage.$emit('refreshWorkorderList', '')
      //   this.$nextTick(() => {
      //     this.item = null
      //     this.selectionWorkersType = null
      //     this.callback = null
      //   })
      // }
      this.$modal({
        title: '抢单确认',
        content: '确认抢单？'
      })
        .then(() => {
          this.$api
            .post('/pg/order/base/qd', {
              orderBaseId: item.id
            })
            .then(res => {
              this.$successToast()
              this.getDetail()
              this.crossPage.$emit('refreshWorkorderList', '')
            })
        })
        .catch(() => {})
    },

    // 去收费
    toCharge(type) {
      if (type == 'M') {
        this.$navToPage({
          url: `/packageMaterial/pages/sale/orderList?type=${type}&oid=${this.id}`
        })
      } else if (type == 'P') {
        this.$navToPage({
          url: `/packageMaterial/pages/newSale/orderList?type=${type}&oid=${this.id}`
        })
      }
    },

    // 去配件申请
    toPartsApply() {
      this.$navToPage({
        url: `/packageMaterial/pages/partsApply/form?id=${this.id}`
      })
    },

    // 去过程反馈
    toFeedback() {
      this.$navToPage({
        url: `/packageWorkorder/pages/processFeedback?id=${this.id}`
      })
    },

    // 去过程反馈列表
    toFeedbackList() {
      this.$navToPage({
        url: `/packageWorkorder/pages/feedbackList?id=${this.id}`
      })
    },

    // 去完工明细
    toOverDetail() {
      this.$navToPage({
        url: `/packageWorkorder/pages/overDetail?id=${this.id}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.all-container {
  position: relative;
}

.bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 300rpx;
  background: linear-gradient(179.48deg, rgba(200, 224, 251, 1) 0.45%, rgba(247, 247, 247, 1) 98.96%);
}

.status-container {
  padding: 30rpx;

  .status {
    font-size: 36rpx;
    font-weight: 500;

    text {
      margin-left: 12rpx;
    }
  }

  .time {
    font-size: 24rpx;
    color: $sec-font;
    margin-top: 12rpx;
  }
}

.tab-container {
  margin-bottom: 30rpx;
}

.card {
  @include zj-card;
}

.common-title {
  font-size: 36rpx;
  font-weight: 600;
  padding-bottom: 20rpx;
}

.common-title2 {
  padding-bottom: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .title {
    font-size: 36rpx;
    font-weight: 600;
  }

  .right {
    font-size: 28rpx;
    color: $theme-color;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    ::v-deep .u-button {
      width: 175rpx;
      margin: 0;
      margin-left: 10rpx;
    }
    text {
      font-size: 28rpx;
      opacity: 0.5;
    }
  }
}

.content-container {
  padding: 0 30rpx 30rpx;
}

.user-container {
  .top {
    padding: 30rpx;

    .type {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left {
        font-size: 36rpx;
        color: $theme-color;
        font-weight: 500;
      }

      .right {
        font-size: 28rpx;
        color: $theme-color;
      }
    }

    .user {
      font-weight: 500;
      margin-top: 20rpx;
    }

    .address {
      display: flex;
      justify-content: space-between;
      margin-top: 20rpx;

      .text {
        font-size: 28rpx;
        flex: 1;
        margin-right: 20rpx;
      }

      .ctrl {
        font-size: 28rpx;
        color: $theme-color;

        .iconfont {
          font-size: 28rpx;
          margin-right: 4rpx;
        }
      }
    }
  }

  .bottom {
    border-top: 1px solid #eaeaea;
    display: flex;
    height: 80rpx;

    .it {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: $theme-color;

      &:last-child {
        border-left: 1px solid #eaeaea;
      }

      .iconfont {
        font-size: 36rpx;
        margin-right: 8rpx;
      }
    }
  }
}

.goods-container {
  padding: 30rpx;

  .item {
    border-bottom: 1px solid #d6e0f2;
    padding: 20rpx 0;

    &:last-child {
      border: none;
    }

    .main {
      display: flex;

      image {
        width: 140rpx;
        height: 140rpx;
        flex-shrink: 0;
      }

      .info {
        flex: 1;
        margin-left: 20rpx;

        .name {
          display: flex;
          justify-content: space-between;

          .left {
            font-weight: 500;
          }

          .right {
            margin-left: 30rpx;
            color: $sec-font;
          }
        }

        .tags {
          display: flex;
          flex-wrap: wrap;

          .it {
            height: 42rpx;
            padding: 0 16rpx;
            background: #f4f5f9;
            border-radius: 8rpx;
            font-size: 24rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 12rpx;
            margin-right: 8rpx;

            &:last-child {
              margin-right: 0;
            }
          }
        }
      }
    }

    .images {
      display: flex;
      flex-wrap: wrap;
      margin-top: 24rpx;

      .it {
        margin-right: 30rpx;

        image {
          width: 116rpx;
          height: 116rpx;
        }

        .text {
          text-align: center;
          color: $sec-font;
          margin-top: 8rpx;
        }
      }
    }
  }

  .ctrl {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 10rpx;

    text {
      color: $sec-font;
    }

    .iconfont {
      font-size: 24rpx;
      transform: rotate(-90deg);
      margin-left: 10rpx;

      &.is {
        transform: rotate(90deg);
      }
    }
  }
}

.info-container {
  padding: 30rpx;

  .row {
    display: flex;
    margin-top: 20rpx;

    &:first-child {
      margin-top: 0;
    }

    .label {
      font-size: 28rpx;
      color: $sec-font;
      margin-right: 20rpx;
      flex-shrink: 0;
    }

    .value {
      font-size: 28rpx;
    }

    .ctrl {
      font-size: 28rpx;
      color: $theme-color;
      margin-left: 20rpx;
    }
  }
}

.product-container {
  padding: 30rpx;
  margin-bottom: 30rpx;

  .row {
    display: flex;

    .label {
      font-size: 28rpx;
      color: $sec-font;
      margin-right: 20rpx;
      flex-shrink: 0;
    }

    .value {
      font-size: 28rpx;
      flex: 1;
    }
  }

  .product {
    background: #f5f5f5;
    border-radius: 12rpx;
    padding: 20rpx;

    .it {
      display: flex;
      align-items: flex-end;
      margin-bottom: 20rpx;

      .name {
        flex: 1;
        font-size: 28rpx;
        font-weight: 500;

        text {
          color: $sec-font;
          margin-left: 12rpx;
          font-weight: normal;
        }
      }

      .price {
        margin-left: 30rpx;
        font-size: 28rpx;
        font-weight: 500;
      }
    }

    .total {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-top: 30rpx;

      .text {
        font-size: 28rpx;
        color: $sec-font;
      }

      .price {
        font-size: 28rpx;
        color: $minor-color;
        font-weight: 500;
      }
    }
  }

  .bottom {
    margin-top: 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
      font-size: 28rpx;
      font-weight: 500;
    }

    .right {
      display: flex;
      align-items: center;

      .text {
        font-size: 28rpx;
        color: $sec-font;
      }

      .price {
        font-size: 28rpx;
        color: $minor-color;
        font-weight: 500;
      }
    }
  }
}

.feedback-container {
  padding: 30rpx;

  .list {
    .item {
      display: flex;
      padding: 10rpx 0;

      .main {
        margin-left: 20rpx;

        .name {
          font-weight: 500;
          line-height: 32rpx;
        }

        .time {
          font-size: 28rpx;
          margin-top: 12rpx;
          color: $sec-font;
          line-height: 32rpx;
        }

        .content {
          font-size: 28rpx;
          margin-top: 12rpx;
          line-height: 32rpx;
        }
      }
    }
  }
}

.bottom-container {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex-wrap: wrap;
  padding: 20rpx 20rpx 20rpx 0;

  ::v-deep .u-button {
    width: 175rpx;
    box-sizing: border-box;
    padding: 10rpx;
    margin: 0;
    margin-left: 10rpx;
    margin-bottom: 10rpx;
  }
}

.feedback-dialog {
  padding: 30rpx 30rpx 0;
  .title {
    margin-bottom: 30rpx;
    text-align: center;
    font-weight: 600;
    font-size: 36rpx;
  }
  .content {
    padding-bottom: 30rpx;
    max-height: 800rpx;
    overflow-y: scroll;
  }
}
.imgs {
  display: flex;
  flex-wrap: wrap;

  .it {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    margin-top: 30rpx;
    margin-right: 30rpx;

    &:nth-child(3n) {
      margin-right: 0;
    }

    image {
      width: 190rpx;
      height: 190rpx;
      background: #f4f4f7;
      border-radius: 20rpx;
      overflow: hidden;
    }

    .name {
      margin-top: 24rpx;
      color: $sec-font;

      text {
        color: $minor-color;
      }
    }
  }
}
</style>
