<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 150px;" placeholder="请输入用户手机" />
      <el-input v-model="listQuery.detailId" clearable class="filter-item" style="width: 160px;"
        placeholder="请输入服务单编号" />
      <el-input v-model="listQuery.orderSn" clearable class="filter-item" style="width: 160px;"
        placeholder="请输入支付订单编号" />

      <el-input v-model="listQuery.goodsId" clearable class="filter-item" style="width: 135px;" placeholder="请输入商品ID" />

      <el-select v-model="listQuery.cityId" filterable clearable style="width: 120px" class="filter-item"
        placeholder="请选择城市">
        <el-option v-for="item in city" :key="item.id" :label="item.cityName" :value="item.id" />
      </el-select>

      <el-select v-model="listQuery.orderStatusArray" clearable multiple class="filter-item" placeholder="请选择服务单状态"
        style="width:150px">
        <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value" />
      </el-select>
      <el-date-picker v-model="listQuery.timeArray" type="datetimerange" class="filter-item" range-separator="至"
        style="width: 340px" start-placeholder="预约开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"
        value-format="yyyy-MM-dd HH:mm:ss" />

      <el-select v-model="listQuery.fraId" style="width: 200px" class="filter-item" placeholder="请选择加盟商" clearable
        filterable>
        <el-option v-for="item in fras" :key="item.id" :label="item.fraName" :value="item.id" />
      </el-select>
      <el-button v-permission="['GET /admin/orderbook/list']" class="filter-item" type="primary" icon="el-icon-search"
        @click="handleFilter">查找
      </el-button>
    </div>

    <el-tabs v-model="listQuery.tab" @tab-click="handleFilter">
      <el-tab-pane label="全部" name="1" />
      <el-tab-pane label="待联系" name="9" />
      <el-tab-pane label="未预约" name="7" />
      <el-tab-pane label="匹配中" name="3" />
      <el-tab-pane label="待履约" name="2" />
      <el-tab-pane label="已约未派加盟商" name="8" />
      <el-tab-pane label="已完成" name="4" />
      <el-tab-pane label="取消" name="5" />
      <el-tab-pane label="挂单" name="6" />
    </el-tabs>

    <!-- 查询结果 -->

    <div :style="{ height: tableHeight }">
      <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row
        :height="tableMaxHeight" :row-class-name="tableRowClassName" @expand-change="handleExpandChange">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-table :data="scope.row.workerInfoList" style="width:1200px;max-height: 400px;overflow-y: auto">
              <el-table-column align="center" label="作业单号" prop="bookDetailServantId" />
              <el-table-column align="center" label="服务者姓名" prop="workerName" />
              <el-table-column align="center" label="服务者电话" prop="workerTel" />
              <el-table-column align="center" label="服务者类型">
                <template slot-scope="scope">
                  {{ scope.row.servantType }}
                </template>
              </el-table-column>

              <el-table-column align="center" label="服务费" prop="servantFee" />
              <el-table-column align="center" label="预估技能退款" prop="refundAmount" />
              <el-table-column align="center" label="服务技能" prop="skillName" />
              <el-table-column align="center" label="服务时间" prop="bookTime">
                <template slot-scope="scope">
                  {{ scope.row.bookDate + " " }}{{ scope.row.bookStartTime }}-{{ scope.row.bookEndTime }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="上门打卡时间" prop="ondoorTime" />
              <el-table-column align="center" label="服务完成时间" prop="finishTime" />
            </el-table>
          </template>
        </el-table-column>

        <el-table-column align="center" :key="Math.random()" label="服务单编号" width="160" prop="id">
          <template slot-scope="scope">
            <div style="text-align: left;">
              <span style="font-weight: 600;">服务单编号:</span>{{ scope.row.id
              }}<br />
              <span style="font-weight: 600;">服务单状态:</span>
              <span style="color:#09afff">
                {{ statusMap[scope.row.status] }} </span><br />
              <span v-show="scope.row.status == 5"><span style="font-weight: 600;">取消原因:</span>
                <span style="color:#09afff">
                  {{ changeReasonMap[scope.row.changeReason] }} </span><br /></span>
              <span style="font-weight: 600;" v-show="scope.row.expectDate">跟进结果:</span>{{ scope.row.expectDate }}<br />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="支付订单编号" width="260" prop="orderSn">
          <template slot-scope="scope">
            <div style="text-align: left;">
              <span style="font-weight: 600;">订单编号:</span>
              {{ scope.row.orderSn }}
              <br />
              <span style="font-weight: 600;">商品名称:</span>
              {{ scope.row.goodsName }}
              <br />
              <span style="font-weight: 600;">支付金额:</span>
              {{ scope.row.actualPrice }}
              <br />
              <span style="font-weight: 600;">加购金额:</span>
              {{ scope.row.increaseSumPrice }}
              <br />
              <span style="font-weight: 600;">加购数量:</span>
              {{ scope.row.increaseDes }}*{{ scope.row.increaseNum }}
              <br />
              <span style="font-weight: 600;">补差项目:</span>
              {{ scope.row.diffName }}<br />
              <span style="font-weight: 600;">补差金额:</span>
              {{ scope.row.diffPrice }}<br />
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="服务单状态" width="105">
            <template slot-scope="scope">
                <el-tag :type="getTagType(scope.row)"> {{ statusMap[scope.row.status] }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column align="center" label="商品名称" prop="goodsName" />-->
        <el-table-column align="center" label="预约信息" prop="consignee" width="340px">
          <template slot-scope="scope">
            <div style="text-align: left;">
              <!-- <span style="font-weight: 600;">预约城市:</span> {{ scope.row.serviceCity }}<br /> -->
              <span style="font-weight: 600;">服务小区:</span>
              {{ scope.row.addressName }}
              <br />
              <span style="font-weight: 600;">服务地址:</span>
              {{ scope.row.serviceCity }} {{ scope.row.address }}
              <br />
              <span style="font-weight: 600;">上门时段:</span>
              {{ scope.row.bookTime }}
              <br />
              <span style="font-weight: 600;">联系电话：</span>
              {{ scope.row.mobile }}
              <br />
              <span style="font-weight: 600;">联系人：</span>
              {{ scope.row.consignee }}
              <br />
              <span style="font-weight: 600;">预约备注：</span>
              {{ scope.row.bookMsg }}
              <br />
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="预约联系方式" prop="mobile" />
        <el-table-column align="center" label="预约时间" prop="bookTime" />
        <el-table-column align="center" label="城市" prop="serviceCity" />
        <el-table-column align="center" label="预约地址" prop="address" />-->
        <el-table-column align="center" label="加盟商" prop="fraName">
          <template slot-scope="scope">
            <div style="text-align: left;">
              <span style="font-weight: 600;">加盟商：</span>
              {{ scope.row.fraName }}
              <br />
              <span style="font-weight: 600;">加盟商电话：</span>
              {{ scope.row.fraTel }}
              <br />
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="加盟商电话" width="145" prop="fraTel" /> -->
        <el-table-column align="center" label="服务人员" prop="servantName" width="200px">
          <template slot-scope="scope">
            <div style="text-align: left;">
              <div v-for="(item, idx) in scope.row.workerInfoList" :key="idx">
                <span style="font-weight: 600;">人员信息{{ idx + 1 }}：</span>{{ item.workerName }}({{ item.servantType }}){{
        item.workerTel }}<br />
                <span style="font-weight: 600;">计提金额{{ idx + 1 }}:</span>{{ item.servantFee }} <br />
              </div>
              <!-- <span style="font-weight: 600;">服务计提：</span>
              {{ scope.row.servantFee }}
              <br /> -->
              <!-- <span style="font-weight: 600;">服务人员：</span>
              {{ scope.row.servantName }}
              <br />
              <span style="font-weight: 600;">联系方式：</span>
              {{ scope.row.servantMobile }}
              <br />
              <span style="font-weight: 600;">人员类型：</span>
              {{
        scope.row.servantName
          ? scope.row.servantType == 0
            ? "全职"
            : "兼职"
          : ""
      }}
              <br /> -->
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="服务人员手机" prop="servantMobile" /> -->
        <el-table-column align="center" label="提醒&更新时间" prop="updateTime" width="220">
          <template slot-scope="scope">
            <div style="text-align: left;">
              <span style="font-weight: 600;">提醒客户:</span>
              {{ scope.row.customerServiceReminder }}
              <br />
              <span style="font-weight: 600;">提醒服务者:</span>
              {{ scope.row.customerServiceSr }}
              <br />
              <span style="font-weight: 600;">更新时间:</span>
              {{ scope.row.updateTime }}
              <br />
              <span style="font-weight: 600;">更新人:</span>
              {{ scope.row.updateUserName }}
              <br />
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="更新人" prop="updateUserName" /> -->

        <el-table-column align="center" label="操作" class-name="small-padding fixed-width" fixed="right" width="250">
          <template slot-scope="scope1">
            <el-button v-permission="['POST /admin/orderbookdetail/changeWorker']" type="primary" plain size="mini"
              @click="handleReassign(scope1.row)" v-show="scope1.row.status == 1 ||
        scope1.row.status == 0 ||
        scope1.row.status == 8 ||
        scope1.row.status == 7
        ">
              {{ scope1.row.status == 0 ? "预约" : "修改预约" }}
            </el-button>
            <el-button v-permission="['GET /admin/orderbook/cancelBook']" type="danger" plain size="mini"
              @click="handleCancel(scope1.row)" v-show="scope1.row.status == 1 || scope1.row.status == 7">取消预约
            </el-button>
            <el-button v-permission="['GET /admin/orderbook/finish']" type="success" plain size="mini"
              @click="handleFinish(scope1.row)" v-show="(scope1.row.status == 1 || scope1.row.status == 2) &&
        scope1.row.servantMobile != ''
        ">完成工单
            </el-button>

            <el-button v-permission="['GET /admin/orderbookdetail/tranBookToFra']" type="info" plain size="mini"
              @click="handleTranBook(scope1.row)" v-show="scope1.row.status == 0 ||
        scope1.row.status == 7 ||
        scope1.row.servantName == '核销假人'
        ">
              调单
            </el-button>
            <el-button v-permission="['POST /admin/orderbookdetail/setWorkerFee']" type="info" plain size="mini"
              @click="handleChangeFee(scope1.row)" v-show="scope1.row.status == 1 ||
        scope1.row.status == 2 ||
        scope1.row.status == 3 ||
        scope1.row.status == 4
        ">
              修改计提
            </el-button>
            <el-button type="warnig" v-permission="['POST /admin/orderbookdetail/notify']" plain size="mini"
              @click="handleNotify(scope1.row)">工单提醒
            </el-button>
            <div v-show="scope1.row.status == 1 ||
        scope1.row.status == 2 ||
        scope1.row.status == 3 ||
        scope1.row.status == 4
        ">
              <el-button type="info" plain size="mini" @click="handleBucha(scope1.row)">补差</el-button>
              <!-- <el-button type="info" plain size="mini" @click="handleBuchaOld(scope1.row)">品类补差</el-button> -->
            </div>
            <el-button type="info" plain size="mini" @click="handleCusAppoint(scope1.row)" v-show="scope1.row.status == 0 ||
        scope1.row.status == 7 ||
        scope1.row.status == 8
        ">客户预约
            </el-button>
            <el-button type="primary" plain size="mini" @click="handleLog(scope1.row)">操作日志</el-button>
            <el-button v-permission="['GET /admin/orderbookdetail/modifyBookState']" type="warning" plain size="mini"
              @click="handleRollback(scope1.row)" v-if="scope1.row.status == 2">回滚到待履约状态</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />



    <!-- 添加备注 提醒到客户或服务者  -->
    <el-dialog :visible.sync="notifyFormVisible" title="追加订单备注" width="800px">
      <el-form ref="notifyForm" :model="notifyForm" status-icon label-position="left" label-width="150px"
        style="width: 700px; ">
        <el-form-item label="提醒服务者" prop="customerServiceSr">
          <el-input v-model="notifyForm.customerServiceSr" type="textarea" placeholder="请输入服务者提醒，此信息会通过服务者小程序 提醒到服务者"
            :autosize="{ minRows: 3, maxRows: 10 }" maxlength="30" oninput="if(value.length>30) value=value.slice(0,50)"
            show-word-limit />
        </el-form-item>
        <el-form-item label="提醒客户" prop="customerServiceReminder">
          <el-input v-model="notifyForm.customerServiceReminder" type="textarea"
            placeholder="请输入提醒内容，您输入的提醒会在小程序端同步展示给客户，请谨慎填写" :autosize="{ minRows: 3, maxRows: 10 }"
            oninput="if(value.length>30) value=value.slice(0,30)" maxlength="30" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="notifyFormVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmNotify">确定</el-button>
      </div>
    </el-dialog>

    <!-- 取消预约对话框 -->
    <el-dialog :visible.sync="cancelAppointVisible" title="取消预约" width="600px">
      <el-form ref="cancelAppointForm" :model="cancelAppointForm" status-icon label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;" :rules="cancelAppointrules">
        <el-form-item label="取消原因" prop="changeReason">
          <el-select v-model="cancelAppointForm.changeReason" placeholder="请选择">
            <el-option v-for="item in cancelReasonList" :key="item.id" :label="item.reason" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAppointVisible = false">取消</el-button>
        <el-button type="primary" @click="cancelBook">确定</el-button>
      </div>
    </el-dialog>

    <!-- 调单给加盟商 -->
    <el-dialog :visible.sync="tranBookFormVisible" title="服务单调单" width="600px">
      <el-form ref="tranBookForm" :model="tranBookForm" status-icon label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;" :rules="cancelAppointrules">
        <el-form-item label="加盟商" prop="fraId">
          <el-select v-model="tranBookForm.fraId" placeholder="请选择加盟商" filterable style="width:300px">
            <el-option v-for="item in fras" :key="item.id" :label="item.fraName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tranBookFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTranBook">确定</el-button>
      </div>
    </el-dialog>

    <!-- 修改计提 -->
    <el-dialog :visible.sync="modifyServiceFeeFormVisible" title="修改工单计提" width="800px">
      <el-form status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">

        <template v-for="item in tempRow.workerInfoList">
          <el-form-item v-if="item.servantType == '兼职'" :key="item.id" :label="item.workerName + '(' + item.servantType + ')'">
            <el-input v-model="item.servantFee" type="number" placeholder="请输入计提金额" />
          </el-form-item>
        </template>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyServiceFeeFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveServiceFee">确定</el-button>
      </div>
    </el-dialog>

    <!-- 操作日志 -->
    <el-dialog :visible.sync="logDiaVisible" title="操作日志" center width="800px">
      <el-table :data="logList" style="width: 100%" border>
        <el-table-column prop="changeType" label="操作类型" align="center">
          <template slot-scope="scope">
            <span v-show="scope.row.changeType == 1">改派</span>
            <span v-show="scope.row.changeType == 2">取消</span>
            <span v-show="scope.row.changeType == 3">调单</span>
            <span v-show="scope.row.changeType == 4">备注</span>
            <span v-show="scope.row.changeType == 5">修改计提</span>
            <span v-show="scope.row.changeType == 6">完成工单</span>
            <span v-show="scope.row.changeType == 7">客户预约</span>
            <span v-show="scope.row.changeType == 8">派单</span>
            <span v-show="scope.row.changeType == 11">流转</span>
            <span v-show="scope.row.changeType == 15">修改客户信息(姓名、电话、地址)</span>
            <span v-show="scope.row.changeType == 16">系统分配加盟商记录</span>
          </template>
        </el-table-column>
        <el-table-column prop="changeReason" width="200px" label="修改原因" />
        <el-table-column prop="oldBookTime" label="旧预约时间" />
        <el-table-column prop="newBookTime" label="新预约时间" />
        <el-table-column prop="createUserName" label="操作人" />
        <el-table-column prop="createTime" label="操作时间" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="logDiaVisible = false">确定</el-button>
      </div>
    </el-dialog>



    <serviceBookRef ref="serviceBookRef" @success="reassignSuccess" />

    <el-dialog :visible.sync="buchaVisit" title="补差二维码" center width="800px">
      <img style="width:480px; height:480px;border:0" :src="buchaUrl" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="buchaVisit = false">确定</el-button>
      </div>
    </el-dialog>

    <!-- 补差列表 -->
    <el-dialog :visible.sync="diffListVisible" title="补差列表" center width="950px">
      <p>
        <el-button type="primary" @click="addDiffOrder">添加</el-button>
      </p>
      <el-table :data="diffList" style="width: 100%" border>
        <el-table-column prop="difName" width="200px" label="补差项" />
        <el-table-column prop="skillName" label="工单技能" />
        <el-table-column prop="difTotalPrice" label="总计金额" />
        <el-table-column prop="state" label="支付状态">
          <template slot-scope="scope">
            {{
        scope.row.state == 0 || scope.row.state == 1
          ? "未支付"
          : scope.row.state == 2
            ? "已支付"
            : "取消"
      }}
          </template>
        </el-table-column>

        <el-table-column prop="createUserName" label="支付时间">
          <template slot-scope="scope">{{
          scope.row.payTime == null ? "" : scope.row.payTime
        }}</template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column align="center" label="操作" fixed="right" width="160">
          <template slot-scope="scope">
            <el-button type="success" plain size="mini" @click="handleEditDiff(scope.row)"
              v-show="scope.row.state == 0">修改
            </el-button>
            <el-button type="info" plain size="mini" @click="handleDiffDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="diffListVisible = false">确定</el-button>
      </div>
    </el-dialog>
    <!-- 添加补差 -->
    <el-dialog :visible.sync="addDiffVisible" :title="(diffOrderType == 'edit' ? '修改' : '创建') + '补差订单'" center
      width="800px">
      <el-form :model="addDiffForm" status-icon label-position="right" label-width="120px"
        style="width: 700px; margin-left:50px;">
        <el-row>
          <el-form-item  label-width="230px" label="选择此工单对应技能创建补差"  >
          <el-radio-group v-model="addDiffForm.skillId" @change="chooseSkill">
            <el-radio v-for="item2 in orderSkillList"  :key="item2.id"  :label="item2.skillId">{{ item2.skillName }}</el-radio> 
          </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row v-for="(item, index) in addDiffForm.diffList" :key="index">
          <el-col :span="10">
            <el-form-item :label="item.itemName" :prop="'diffList.' + index + '.number'" :rules="{
        validator: isNumber,
        message: '份数只能为正整数',
        trigger: 'change'
      }">
              <el-input v-model="item.number" type="number" placeholder="请输入份数"
                @change="diffNumberChange(item.number, item.price, index)" style="width:160px" />
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="2">
            <el-form-item label="金额:(元)">
              <el-input v-model="item.difTotalPrice" type="number" :placeholder="'金额为:' + item.price2"
                style="width:160px" @change="
        diffNumberChange(item.number, item.difTotalPrice, index)
        " disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <p style="font-weight:bold;">总计补差金额:{{ totalDiffAmount }}</p>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addDiffVisible = false">取消</el-button>
        <el-button type="primary" @click="confAddDiff">确定</el-button>
      </div>
    </el-dialog>
    <!-- 补差详情 -->
    <el-dialog :visible.sync="diffDetailVisible" title="补差订单详情" center width="700px">
      <el-row>
        <el-col :span="12">补差内容：{{ diffDetailInfo.difName }}</el-col>
        <el-col :span="12">金额：{{ diffDetailInfo.difTotalPrice }}</el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :span="12">创建时间：{{ diffDetailInfo.createTime }}</el-col>
        <el-col :span="12">支付状态：{{
        diffDetailInfo.state == 0 || diffDetailInfo.state == 1
          ? "未支付"
          : diffDetailInfo.state == 2
            ? "已支付"
            : "取消"
      }}
        </el-col>
      </el-row>
      <br />
      <el-table :data="diffDetailList" style="width: 100%" border>
        <el-table-column prop="itemName" width="200px" label="补差项" />
        <el-table-column prop="number" label="份数" />
        <el-table-column prop="difTotalPrice" label="金额" />
      </el-table>
      <div style="text-align:center;">
        <p>补差二维码</p>
        <img style="width:320px; height:320px;border:0" :src="diffDetailInfo.qrUrl" />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="diffDetailVisible = false">确定</el-button>
      </div>
    </el-dialog>

    <!-- 客户预约 -->
    <el-dialog :visible.sync="cusAppointVisible" title="客户预约" center width="800px">
      <div style="min-height:200px; text-align:center;margin:10px 0 20px;">
        <el-row>
          <sapn>预约方式:</sapn>
          <el-radio-group v-model="cusAppointType">
            <el-radio :label="1">二维码</el-radio>
            <el-radio :label="2">短链</el-radio>
          </el-radio-group>
        </el-row>
        <p>
          <el-button type="success" @click="confCusAppoint" size="mini">确定</el-button>
        </p>
        <p v-show="cusAppointLink" style="margin-top:40px;">
          短链地址：<span style="font-size:18px;font-weight:bold;">{{
        cusAppointLink
      }}</span>
        </p>
        <img style="width:480px; height:480px;border:0" :src="cusAppointUrl" v-show="cusAppointUrl" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="cusAppointVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <!-- 回滚对话框 -->

    <el-dialog title="提示" width="400px" :visible.sync="rollBackVisible">
      <h2>是否确认回滚到待履约状态？</h2>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rollBackVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRollBack">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOrderBookDetailList,
  setWorkerFee,
  notify,
  tranBookToFra
} from "@/api/orderBookDetail";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { formatDate } from "@/utils/date";
import { getUserCity } from "@/api/city";
import {
  bucha,
  cancelBook,
  createCustomerBookQrCode,
  getAllFras,
  getAssignmentPerson,
  getAssignmentPersonTime,
  getOpLog,
  orderBookFinish,
  orderBookReassign
} from "@/api/order";
import {
  createDiffOrder,
  getDiffDetail,
  getDiffOrderList,
  getDiffTypeList,
  modifyBookState
} from "@/api/diffOrder";
import {
  bookStatusMap,
  cancelReasonList,
  cancelReasonMapList
} from "@/api/enumUtils";
import serviceBookRef from "../order/components/serviceBookRef";
import { detail } from "@/api/commission";
let vm;
export default {
  name: "serviceBook",
  components: { Pagination, serviceBookRef },
  filters: {
    orderStatusFilter(status) {
      return statusMap[status];
    }
  },
  data() {
    return {
      tableHeight: "560px", //表控件高度
      fras: [],
      changeReasonMap: cancelReasonMapList,
      assignOrderId: "",
      assignOrderStatus: "",
      timerange: [],
      cancelAppointVisible: false,
      cancelOrderItem: "",
      cancelAppointrules: {
        changeReason: [
          { required: true, message: "请选择取消原因", trigger: "change" }
        ]
      },
      cancelAppointForm: {
        changeReason: ""
      },
      cancelReasonList: cancelReasonList,
      tranBookFormVisible: false,
      tranBookForm: {
        id: "",
        fraId: ""
      },
      // modifyServiceFeeForm: {
      //   //计提
      //   id: "",
      //   servantFee: ""
      // },
      modifyServiceFeeFormVisible: false,
      // modifyServiceFeerules: {
      //   servantFee: [
      //     { required: true, message: "请输入计提金额", trigger: "blur" }
      //   ]
      // },
      notifyFormVisible: false,
      notifyForm: {
        id: "",
        customerServiceSr: "", //提醒到服务者
        customerServiceReminder: "", //提醒到客户
        orderId: "",
        orderSn: ""
      },
      timeList: [],
      timeListAppoint: [],
      servantList: [],
      list: [],
      total: 0,
      listLoading: false,
      city: [],
      listQuery: {
        page: 1,
        limit: 20,
        mobile: "",
        timeArray: [],
        detailId: "",
        orderSn: this.$route.query.orderSn,
        orderStatusArray: [],
        cityId: "",
        sort: "create_time",
        order: "desc",
        tab: "3"
      },
      rules: {
        bookDate: [
          { required: true, message: "请选择改派日期", trigger: "blur" }
        ],
        bookTime: [
          { required: true, message: "请选择改派时间", trigger: "blur" }
        ],
        servantId: [
          { required: true, message: "请选择服务者", trigger: "blur" }
        ],
        fraId: [{ required: true, message: "请选择加盟商", trigger: "blur" }]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      statusMap: bookStatusMap,
      orderDialogVisible: false,
      orderDetail: [],
      reassignForm: {
        id: "",
        bookDate: "",
        bookTime: "",
        servantId: "",
        orderId: ""
      },
      logDiaVisible: false,
      logList: [],
      buchaVisit: false,
      buchaUrl: "",
      diffListVisible: false,
      diffList: [],
      diffTypeList: [],
      orderSkillList: [],
      addDiffVisible: false,
      addDiffForm: {
        diffList: [
          {
            difTotalPrice: "",
            difTotalPrice2: "",
            price2: ""
          }
        ],
        diffId: 0,
        bookDetailId: "",
        skillId: '',
        skillName: ''
      },
      totalDiffAmount: 0,
      diffDetailVisible: false,
      diffOrderType: "",
      diffDetailList: [],
      diffDetailInfo: {},
      cusAppointVisible: false,
      cusAppointId: "",
      cusAppointUrl: "",
      cusAppointLink: "",
      cusAppointType: 1,
      rollBackVisible: false,
      detailId: "",
      tempRow: {
        workerInfoList: []
      }
    };
  },
  computed: {
    tableMaxHeight() {
      this.tableHeight =
        window.innerHeight - (window.innerWidth > 1800 ? 280 : 330) + "px";
      return this.tableHeight;
    }
  },
  beforeCreate() {
    vm = this;
  },
  created() {
    if (this.$route.query.orderSn) {
      this.listQuery.orderSn = this.$route.query.orderSn;
    }
    if (this.$route.query.orderId) {
      this.listQuery.orderId = this.$route.query.orderId;
    }
    this.getList();
    getUserCity().then(res => {
      this.city = res.data.data;
    });
    this.getAllFras();
  },
  methods: {
    isNumber(rule, value, callback) {
      if (value == 0 || value == "") {
        return callback();
      } // 这是用来判断如果不是必须输入的，则直接跳出
      const r = /^\+?[1-9][0-9]*$/; // 正整数
      // 如果判断不符合正则，则不是正整数不能提交
      if (!r.test(value)) {
        return callback(new Error("数量必须为正整数"));
      } else {
        return callback();
      }
    },
    getList() {
      this.listLoading = true;
      if (this.listQuery.timeArray && this.listQuery.timeArray.length === 2) {
        this.listQuery.start = this.listQuery.timeArray[0];
        this.listQuery.end = this.listQuery.timeArray[1];
      } else {
        this.listQuery.start = null;
        this.listQuery.end = null;
      }
      try {
        getOrderBookDetailList(this.listQuery)
          .then(response => {
            this.list = response.data.data.list;
            this.total = response.data.data.total;
            this.listLoading = false;
          })
          .catch(() => {
            this.list = [];
            this.total = 0;
            this.listLoading = false;
          });
      } catch (e) {
        console.log(e);
        this.listLoading = false;
      }
    },
    getAllFras() {
      getAllFras().then(res => {
        this.fras = res.data.data;
      });
    },
    handleNotify(row) {
      this.notifyFormVisible = true;
      this.notifyForm = {
        id: row.id,
        customerServiceReminder: row.customerServiceReminder,
        customerServiceSr: row.customerServiceSr,
        orderId: row.orderId,
        orderSn: row.orderSn
      };
    },
    confirmNotify() {
      //保存提醒
      // if (
      //   !this.notifyForm.customerServiceReminder &&
      //   !this.notifyForm.customerServiceSr
      // ) {
      //   this.$message.warning("请至少填写一个提醒客户或提醒服务者");
      //   return;
      // }
      notify(this.notifyForm)
        .then(res => {
          for (const v of this.list) {
            if (v.id === this.notifyForm.id) {
              v.customerServiceReminder = this.notifyForm.customerServiceReminder;
              v.customerServiceSr = this.notifyForm.customerServiceSr;
              break;
            }
          }
          this.notifyFormVisible = false;
          this.$message.success("更新成功");
        })
        .catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
    },
    handleTranBook(row) {
      //调单给加盟商
      if (row.servantId) {
        this.$notify.error({
          title: "失败",
          message: "请先取消订单 才可以调单"
        });
        return;
      }
      this.tranBookFormVisible = true;
      this.tranBookForm = {
        fraId: row.fraId,
        bookDetailId: row.id
      };
    },
    saveTranBook() {
      if (this.tranBookForm.fraId == null || this.tranBookForm.fraId == "") {
        this.$notify.error({
          title: "失败",
          message: "请选择加盟商"
        });
        return;
      }
      this.$confirm("确定将此服务单调配给此加盟商？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        tranBookToFra(this.tranBookForm)
          .then(res => {
            this.tranBookFormVisible = false;
            this.$message.success("调单成功");
            this.getList();
          })
          .catch(response => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg
            });
          });
      });
    },
    handleChangeFee(row) {
      //修改计提
      this.modifyServiceFeeFormVisible = true;
      this.tempRow = row;
      // this.modifyServiceFeeForm = {
      //   id: row.id,
      //   servantFee: row.servantFee
      // };
    },
    saveServiceFee() {
      let feeList = [];
      this.tempRow.workerInfoList.forEach(e => {
        if (e.servantType == '兼职') {
          feeList.push({ workerId: e.workerId, workerFee: e.servantFee });
        }
      })


      let req = {
        detailId: this.tempRow.id,
        workerServiceFeeList: feeList
      };
      setWorkerFee(req)
        .then(res => {
          // for (const v of this.list) {
          //   if (v.id === this.modifyServiceFeeForm.id) {
          //     v.servantFee = this.modifyServiceFeeForm.servantFee;
          //     break;
          //   }
          // }
          this.$message.success("计提修改成功");
          this.modifyServiceFeeFormVisible = false;
        })
        .catch(res => {
          this.$notify.error({
            title: "失败",
            message: res.data.errmsg
          });
        });


    },
    formatTime(time) {
      if (time == null || time === "") {
        return "";
      }
      const date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleCancel(row) {
      this.cancelOrderItem = row;
      this.cancelAppointVisible = true;
    },
    cancelBook() {
      this.$refs["cancelAppointForm"].validate(valid => {
        if (valid) {
          let params = {
            detailId: this.cancelOrderItem.id,
            changeReason: this.cancelAppointForm.changeReason
          };
          cancelBook(params)
            .then(response => {
              this.$message.success("取消成功");
              this.cancelAppointVisible = false;
              this.cancelOrderItem.status = 5;
            })
            .catch(response => {
              this.$notify.error({
                title: "失败",
                message: response.data.errmsg
              });
            });
        }
      });
    },
    handleReassign(row) {
      let data = { id: row.id, orderId: row.orderId, fraId: row.fraId };
      this.$refs.serviceBookRef.init(data);
    },
    reassignSuccess(data) {
      this.getList();
    },
    handleFinish(row) {
      this.$confirm("确定要手动核销完成此服务单吗！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        orderBookFinish({ id: row.id })
          .then(response => {
            this.$message.success("完结成功");
            row.status = 4;
          })
          .catch(response => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg
            });
          });
      });
    },
    getServantList(id) {
      getAssignmentPerson(id).then(res => {
        this.servantList = res.data.data;
      });
    },
    getAppointTime() {
      if (
        this.reassignForm.bookDate == "" ||
        this.reassignForm.bookDate == null
      ) {
        this.$message.warning("请先选择日期");
        return false;
      } else if (this.reassignForm.servantId == "") {
        this.$message.warning("请先选择服务者");
        return false;
      } else {
        let list = [];
        this.timeList.forEach(item => {
          let obj = {
            startTime: item.split("-")[0],
            endTime: item.split("-")[1]
          };
          list.push(obj);
        });
        let params = {
          workerId: this.reassignForm.servantId,
          reservationDate: this.reassignForm.bookDate,
          timesList: list
        };
        getAssignmentPersonTime(params)
          .then(res => {
            console.log(res);
            let reslist = res.data.data.timesList;
            this.timeListAppoint = reslist.map(item => {
              return item.startTime + "-" + item.endTime;
            });
          })
          .catch(response => { });
      }
    },
    servantChange(value) {
      console.log(value);
      this.timeListAppoint = [];
      this.reassignForm.bookTime = "";
    },
    wholeModify() {
      this.$confirm("若工单预约时间为空需要单独修改预约！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        onceReassign(this.assignOrderId)
          .then(res => {
            console.log(res);
            if (res.data.errno == 0) {
              this.$notify.success({
                title: "成功",
                message: "改派成功"
              });
              this.orderBookDetail(this.assignOrderId);
            } else {
              this.$message.error(res.data.errmsg);
            }
          })
          .catch(err => {
            console.log(err);
            this.$message.error(err.data.errmsg);
          });
      });
    },
    getTagType(row) {
      if (row.status == 0) return "";
      if (row.status == 1) return "info";
      if (row.status == 2 || row.status == 3) return "warning";
      if (row.status == 4 || row.status == 5) return "success";
      return "danger";
    },
    tableRowClassName({ row, index }) {
      return "";
      if (row.status == 5 || row.status == 6) {
        return "";
      } else if (row.status == 1) {
        return "waiting";
      } else if (row.status == 2) {
        return "processing";
      } else if (row.status == 3 || row.status == 4) {
        return "completed";
      } else if (row.status == 0) return "nobook";
      return "accept"; //待接单
    },
    handleLog(row) {
      this.logDiaVisible = true;
      getOpLog({ serviceId: row.id })
        .then(res => {
          this.logList = res.data.data.list;
        })
        .catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
    },
    handleBuchaOld(row) {
      this.buchaVisit = true;
      this.buchaUrl = "";
      let param = {
        serviceId: row.id,
        fraId: row.fraId,
        resource: "mall"
      };
      bucha(param)
        .then(res => {
          if (res.data.errno === 0) {
            this.buchaUrl = res.data.data;
          }
        })
        .catch(res => {
          this.$notify.error({
            title: "失败",
            message: res.data.errmsg
          });
        });
    },
    handleBucha(row) {
      this.diffListVisible = true;
      this.addDiffForm.bookDetailId = row.id;
      this.getDiffList();
    },
    getDiffList() {
      getDiffOrderList({ bookDetailId: this.addDiffForm.bookDetailId })
        .then(res => {
          this.diffList = res.data.data;
        })
        .catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
    },
    handleDiffDetail(row) {
      getDiffDetail({ diffOrderId: row.id })
        .then(res => {
          this.diffDetailInfo = res.data.data;
          this.diffDetailList = res.data.data.itemList;
          this.diffDetailVisible = true;
        })
        .catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
    },
    diffNumberChange(num, price, index) {
      /*console.log(num)
      console.log(price)
      console.log(this.addDiffForm.diffList[index].difTotalPrice2)
      console.log(this.addDiffForm.diffList[index].price)*/
      if (price < this.addDiffForm.diffList[index].price2) {
        this.$message.warning(
          "价格不能超过最低价" + this.addDiffForm.diffList[index].price2
        );
        this.addDiffForm.diffList[
          index
        ].difTotalPrice = this.addDiffForm.diffList[index].price2;
        price = this.addDiffForm.diffList[index].price2;
      }
      this.addDiffForm.diffList[index].difTotalPrice2 = Number(
        num * price
      ).toFixed(2);
      this.addDiffForm.diffList[index].price = price;
      let total = 0;
      this.addDiffForm.diffList.forEach(item => {
        if (item.difTotalPrice2 != undefined && item.difTotalPrice2 != "") {
          total += Number(item.difTotalPrice2);
        }
      });
      this.totalDiffAmount = total;
    },
    addDiffOrder() {
      this.diffOrderType = "create";
      this.addDiffVisible = true;
      this.addDiffForm.diffId = 0;
      this.addDiffForm.skillId = '';
      this.totalDiffAmount = 0;
      getDiffTypeList({ bookDetailId: this.addDiffForm.bookDetailId })
        .then(res => {
          this.addDiffForm.diffList = res.data.data.diffList;
          this.orderSkillList = res.data.data.orderSkillList; 
          this.addDiffForm.diffList.forEach(item => {
            item.price2 = item.price;
          });
        })
        .catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
    },
    handleEditDiff(row) {
      this.diffOrderType = "edit";
      this.addDiffForm.diffId = row.id;
      this.addDiffForm.skillId = row.skillId+'';
      this.addDiffForm.skillName = row.skillName;
      getDiffDetail({ diffOrderId: row.id })
        .then(res => {
          this.totalDiffAmount = res.data.data.difTotalPrice;
          this.addDiffForm.diffList = res.data.data.itemList;
          this.orderSkillList=res.data.data.orderSkillList;
          this.addDiffVisible = true;
        })
        .catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
    },
    chooseSkill(skid){
      let nm='';
      this.orderSkillList.forEach(e=>{
        if(e.skillId==skid){
          nm=e.skillName;
        }
      })
      this.addDiffForm.skillName=nm;
    },
    confAddDiff() {
      //  let list=this.addDiffForm.diffList.filter(item=>{return item.number>0});
      let list = this.addDiffForm.diffList;
      createDiffOrder({
        bookDetailId: this.addDiffForm.bookDetailId,
        diffId: this.addDiffForm.diffId,
        skillId:this.addDiffForm.skillId,
        skillName:this.addDiffForm.skillName,
        diffList: list
      })
        .then(res => {
          this.addDiffVisible = false;
          this.getDiffList();
        })
        .catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
    },
    handleCusAppoint(row) {
      this.cusAppointVisible = true;
      this.cusAppointId = row.id;
      this.cusAppointUrl = "";
      this.cusAppointLink = "";
      this.cusAppointType = 1;
    },
    confCusAppoint() {
      createCustomerBookQrCode({
        serviceId: this.cusAppointId,
        type: this.cusAppointType
      })
        .then(res => {
          if (res.data.errno === 0) {
            if (this.cusAppointType == 1) {
              this.cusAppointUrl = res.data.data;
            } else {
              this.cusAppointLink = res.data.data;
            }
          }
        })
        .catch(res => {
          this.$notify.error({
            title: "失败",
            message: res.data.errmsg
          });
        });
    },
    handleRollback(row) {
      this.rollBackVisible = true;
      console.log(row);
      this.detailId = row.id;
    },
    confirmRollBack() {
      modifyBookState({ detailId: this.detailId })
        .then(res => {
          console.log("22", res);
          if (res.data.errno == 0) {
            this.$notify.success({
              title: "成功",
              message: res.data.errmsg,
              duration: 2000
            });
            this.rollBackVisible = false;
            this.getList()
          }
        })
        .catch(res => {
          this.$notify.error({
            title: "失败",
            message: res.data.errmsg
          })
        })
    },
    handleExpandChange(row, expandRows) {

    }
  }
};
</script>

<style scoped>
.el-table .accept {
  background-color: #cc5858;
}

.el-table .completed {
  background-color: #999;
}

.el-table .waiting {
  background-color: #73bfec;
}

.el-table .nobook {
  background-color: #bebbbb;
}

.el-table .cancel {
  background-color: #bebbbb;
}

.el-table .processing {
  background-color: rgb(169 201 234);
}

.el-table th.gutter {
  display: table-cell !important;
}

.pagination-container {
  margin-top: 0px;
  padding: 5px 16px !important;
}

.detail-container {
  width: 80%;
  padding: 20px 20px 20px 20px;
  margin: 20px auto;
}

.operate-container {
  background: #f2f6fc;
  height: 80px;
  margin: -20px -20px 0;
  line-height: 80px;
}

.operate-button-container {
  float: right;
  margin-right: 20px;
}

.table-layout {
  margin-top: 20px;
  border-left: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
}

.table-cell {
  height: 60px;
  line-height: 20px;
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  white-space: pre-wrap;
  /* overflow: hidden; */
}

.table-cell-title {
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  background: #f2f6fc;
  text-align: center;
  font-size: 14px;
  color: #303133;
}

.el-table th.gutter {
  display: table-cell !important;
}

.color-danger {
  color: #f56c6c;
  font-size: 18px;
}

.warn-color {
  color: #f56c6c;
}

.fixed-width .el-button--mini {
  width: auto;
  min-width: 55px;
}

.cell .el-button.is-plain {
  margin-bottom: 10px;
}
</style>
