<template>
  <div class="app-container">
    <!-- 扣车单位 -->
    <div class="left">
      <div class="left_top">
        当前选择的是:&nbsp;&nbsp;{{ chooseData.buckleName }}
      </div>
      <el-input placeholder="请输入名称" size="small" style="margin:1rem 0 1rem 0" v-model="filterText"/>
      <el-skeleton v-if="treeLoading"/>
      <el-tree v-else @check="handleSelectionChange" :data="dictDataTree" ref="tree"
               :filter-node-method="filterNode"
               @node-click="handleNodeClick"
               highlight-current
               :default-checked-keys="[chooseData.id]"
      >
        <template v-slot="{ node, data }">
          <!-- 自定义节点内容 -->
          <span class="custom-tree-node">
        {{ truncateText(data.buckleName, 15) }}
      </span>
        </template>
      </el-tree>
    </div>

    <!-- 具体表格 -->
    <div class="right">
      <!-- 搜索栏 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="名称" prop="connectionName">
          <el-input
            v-model="queryParams.connectionName"
            placeholder="请输入客户名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="客户车牌号" prop="licenseNum">
          <el-input
            v-model="queryParams.licenseNum"
            placeholder="请输入车牌号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="司机名称" prop="driverName">
          <el-input
            v-model="queryParams.driverName"
            placeholder="请输入司机名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="司机车牌号" prop="driverCarNum">
          <el-input
            v-model="queryParams.driverCarNum"
            placeholder="请输入救援车辆车牌号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="扣车状态" prop="rescueStatus">
          <el-select v-model="queryParams.rescueStatus" placeholder="请选择收费类型" clearable>
            <el-option
              v-for="dict in this.getDictDatas(DICT_TYPE.RESCUE_STATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="扣车时间" prop="maintenanceTime">
          <el-date-picker
            v-model="timeArray"
            type="daterange"
            value-format="yyyy-MM-dd"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计 -->
      <div style="margin-bottom: 1rem">
        <el-row style="display: flex;justify-content: space-between">
          <el-col :span="4">
            <div>
              <el-statistic :value="buckleCount" title="总扣车"/>
            </div>
          </el-col>
          <el-col :span="4">
            <div>
              <el-statistic :value="deductionCount" title="扣车中"/>
            </div>
          </el-col>
          <el-col :span="4">
            <div>
              <el-statistic :value="unDeductionCount" title="已解扣"/>
            </div>
          </el-col>
          <el-col :span="4">
            <div>
              <el-statistic :value="returnCount" title="已还车"/>
            </div>
          </el-col>
          <el-col :span="4">
            <div>
              <el-statistic :value="noLibraryCount" title="待入库"/>
            </div>
          </el-col>
        </el-row>
      </div>

      <el-row style="margin: 1rem 0" :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-download" :loading="exportLoading" size="mini" @click="handleExport">
            导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getTabList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="infoList">
        <el-table-column label="序号" align="center">
          <template scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="扣车单位" prop="deptId" align="center">
          <template scope="scope">
            <span>{{ getBuckleName(scope.row.deptId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户信息" align="center">
          <el-table-column label="姓名" align="center" prop="connectionName"/>
          <el-table-column label="手机号" width="130" align="center" prop="connectionPhone"/>
          <el-table-column label="车牌号" width="150" align="center" prop="licenseNum">
            <template slot-scope="scope">
              <span v-if="editType===0 && scope.$index == editIdx"><el-input v-model="scope.row.licenseNum "></el-input><i
                @click="editInfo(scope.row)" class="el-icon-check"></i></span>
              <span v-else>{{ scope.row.licenseNum }}<i @click="editInfoFront(0,scope.$index)" class="el-icon-edit"></i></span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="救援司机" align="center">
          <el-table-column label="姓名" align="center" prop="driverName"/>
          <el-table-column label="手机号" width="130" align="center" prop="driverPhoneNum"/>
          <el-table-column label="车牌号" width="120" align="center" prop="driverCarNum">
            <template slot-scope="scope">

              <span v-if="editType===1 && scope.$index == editIdx"><el-input
                v-model="scope.row.driverCarNum "></el-input><i @click="editInfo(scope.row)" class="el-icon-check"></i></span>
              <span v-else>{{ scope.row.driverCarNum }}<i @click="editInfoFront(1,scope.$index)"
                                                          class="el-icon-edit"></i></span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="救援时间" width="100" align="center" prop="rescueTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.rescueTime, '{y}-{m}-{d} {h}:{m}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="救援类型" align="center" prop="rescueType">
          <template slot-scope="scope">
            <dict-tag :type="DICT_TYPE.DLJY_TYPE" :value="scope.row.rescueType"/>
          </template>
        </el-table-column>
        <el-table-column label="路段" align="center" prop="sectionRoad"/>
        <el-table-column label="车辆类型" align="center" prop="carType">
          <template slot-scope="scope">
            <dict-tag :type="DICT_TYPE.RESCUE_CAR_TYPE" :value="scope.row.carType"/>
          </template>
        </el-table-column>
        <el-table-column width="130" label="救援地点" :show-overflow-tooltip="true" align="center"
                         prop="rescuePosition"/>
        <el-table-column label="收费类型" align="center" prop="feeType">
          <template slot-scope="scope">
            <dict-tag :type="DICT_TYPE.FEE_TYPE" :value="scope.row.feeType"/>
          </template>
        </el-table-column>
        <el-table-column label="救援状态" align="center" prop="rescueStatus">
          <template slot-scope="scope">
            <dict-tag :type="DICT_TYPE.JY_STATUS" :value="scope.row.rescueStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="订单状态·" align="center" prop="orderStatus">
          <template slot-scope="scope">
          <span v-if="scope.row.orderStatus">
             <dict-tag :type="DICT_TYPE.JY_ORDER_STATUS" :value="scope.row.orderStatus"/>
          </span>
            <span v-else>
            未成单
         </span>
          </template>
        </el-table-column>

        <el-table-column label="应收金额(元)" width="150" align="center" prop="setMoney">
          <template slot-scope="scope">

            <span v-if="editType===2 && scope.$index == editIdx"><el-input oninput="value=value.replace(/[^0-9.]/g,'')"
                                                                           v-model="scope.row.setMoney2 "></el-input><i
              @click="editInfo(scope.row,2)" class="el-icon-check"></i></span>
            <span v-else>{{ scope.row.setMoney / 100 }}<i @click="editInfoFront(2,scope.$index)"
                                                          class="el-icon-edit"></i></span>
          </template>
        </el-table-column>
        <el-table-column label="实收金额(元)" width="150" align="center" prop="payMoney">
          <template slot-scope="scope">
            <span>{{ scope.row.payMoney / 100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收款时间" align="center" width="100" prop="payTime">
          <template slot-scope="scope">
            <span>{{ scope.row.payTime }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="150" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-if="scope.row.rescueStatus === '6'"
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="openReturnCar(scope.row)"
            >还车
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-bottom: 10rem">
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNo"
          :limit.sync="queryParams.pageSize"
          @pagination="getTabList"
        />
      </div>
    </div>

    <el-dialog title="车辆归还" :visible.sync="returnCar" width="80%" append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-card class="box-card">
          <!-- 卡片头 -->
          <div slot="header" class="clearfix">
            <i class="el-icon-plus"/>
            <span>客户信息</span>
          </div>
          <!-- 卡片内容 -->
          <div>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="姓名" prop="connectionName">
                  <el-input disabled v-model="formData.connectionName" placeholder="请输入资产编号"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="connectionPhone">
                  <el-input disabled v-model="formData.connectionPhone" placeholder="请输入资产编号"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="车牌号" prop="licenseNum">
                  <el-input disabled v-model="formData.licenseNum" placeholder="请输入资产编号"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收费类型" prop="feeType">
                  <el-select disabled v-model="formData.feeType" clearable filterable placeholder="请选择存放位置" class="customerSelectWidth">
                    <el-option v-for="item in this.getDictDatas(DICT_TYPE.FEE_TYPE)" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="订单状态" prop="orderStatus">
                  <el-select disabled v-model="formData.orderStatus" clearable filterable placeholder="请选择存放位置"
                             class="customerSelectWidth">
                    <el-option v-for="item in this.getDictDatas(DICT_TYPE.JY_ORDER_STATUS)" :key="item.value"
                               :label="item.label" :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="应收金额(元)" prop="setMoney">
                  <el-input disabled v-model="formData.setMoney" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="实收金额(元)" prop="payMoney">
                  <el-input disabled v-model="formData.payMoney"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收款时间" prop="payTime">
                  <el-date-picker disabled clearable v-model="formData.payTime" type="date" value-format="yyyy-MM-dd"
                                  placeholder="选择取得日期"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <el-card class="box-card">
          <!-- 卡片头 -->
          <div slot="header" class="clearfix">
            <i class="el-icon-plus"/>
            <span>附件信息</span>
          </div>
          <!-- 卡片内容 -->
          <div>
            <el-form-item label="附件信息" prop="images">
              <FileUpload ref="fileUpload" v-model="formData.images" :limit="50" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="formData.remark" maxlength="200"
                        show-word-limit/>
            </el-form-item>
          </div>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleReturn" :disabled="formLoading">确 定</el-button>
        <el-button @click="returnCar = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {delInfo, returnCar, downloadOrder, listBuckle, listInfo, updateInfo, getBuckle} from "@/api/rescue/info";
import {DICT_TYPE} from "@/utils/dict";

export default {
  name: "BuckleList",
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    }
  },
  data() {
    return {
      // 导出遮罩层
      exportLoading: false,
      // 遮罩层
      loading: true,
      filterText: '',
      chooseData: '',
      dictDataTree: [],
      // 加载遮罩
      treeLoading: true,
      // 查询参数
      queryParams: {
        licenseNum: null,
        pageNo: 1,
        pageSize: 10,
        connectionName: null,
        isAppointment: null,
        rescueType: null,
        feeType: null,
        carBrand: null,
        destinationInfo: null,
        rescueStatus: null,
        rescueAmount: null,
        driverName: null,
        driverCarNum: null,
        orderStatus: null,
        rescueEnd: null,
        rescueStart: null,
        deptId: null,
      },
      // 显示搜索条件
      showSearch: true,
      pickerOptions: null,
      timeArray: [],
      infoList: [],
      total: 0,
      editType: 0,
      editIdx: -1,
      // 扣车总数
      buckleCount: 0,
      // 扣车中
      deductionCount: 0,
      // 已解扣
      unDeductionCount: 0,
      // 已还车
      returnCount: 0,
      // 待入库
      noLibraryCount: 0,
      returnCar: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        connectionName: null,
        connectionPhone: null,
        licenseNum: null,
        feeType: null,
        orderStatus: null,
        setMoney: null,
        payMoney: null,
        payTime: null,
        images: null,
        remark: null,
      },
      // 表单校验
      formRules: {
      },
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    chooseData(val){
      if (val){
        this.buckleCount = val.buckleCount
        this.deductionCount = val.deductionCount
        this.unDeductionCount = val.unDeductionCount
        this.returnCount = val.returnCount
        this.noLibraryCount = val.noLibraryCount
      }
    },
  },
  created() {
    this.getList()
    this.getTabList()
  },
  methods: {
    async getList() {
      try {
        this.treeLoading = true
        const response = await listBuckle();
        this.dictDataTree = response.data
        await this.initStatistic(response.data)
      } finally {
        this.treeLoading = false
      }
    },
    async initStatistic(data){
      this.buckleCount = data.reduce((temp, item) => {
        return temp + item.buckleCount
      }, 0)
      this.deductionCount = data.reduce((temp, item) => {
        return temp + item.deductionCount
      }, 0)
      this.unDeductionCount = data.reduce((temp, item) => {
        return temp + item.unDeductionCount
      }, 0)
      this.returnCount = data.reduce((temp, item) => {
        return temp + item.returnCount
      }, 0)
      this.noLibraryCount = data.reduce((temp, item) => {
        return temp + item.noLibraryCount
      }, 0)
    },
    handleSelectionChange(selection) {
      const flag = this.selectNodes.findIndex(item => item.dataId === selection.dataId)
      if (flag > -1) {
        this.selectNodes.splice(flag, 1)
      } else {
        this.selectNodes.push(selection)
      }
      this.deleteMultiple = !this.selectNodes.length > 0
      this.updateMultiple = !(this.selectNodes.length === 1)
    },
    // 节点筛选
    filterNode(value, data) {
      if (!value) return true
      return data.buckleName.indexOf(value) !== -1
    },
    // 节点事件
    handleNodeClick(e) {
      this.chooseData = e
      this.queryParams.deptId = e.id
      this.getTabList()
    },
    truncateText(text, maxLength) {
      if (text.length > maxLength) {
        return text.substring(0, maxLength) + '...'
      }
      return text
    },
    handleQuery() {
      this.queryParams.pageNo = 1
      if (this.timeArray && this.timeArray.length > 0) {
        this.queryParams.rescueStart = this.timeArray[0];
        this.queryParams.rescueEnd = this.timeArray[1];
      }
      this.getTabList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.rescueStart = null
      this.queryParams.rescueEnd = null
      this.timeArray = null
      this.resetForm('queryForm')
      this.handleQuery()
    },
    async getTabList() {
      try {
        this.loading = true
        this.queryParams.rescueType = '5'
        const res = await listInfo(this.queryParams)
        this.infoList = res.data.records
        this.total = res.data.total
      } finally {
        this.loading = false
      }
    },
    /** 导出按钮操作 */
    async handleExport() {
      try {
        this.exportLoading = true
        this.queryParams.pageNo = 1
        this.queryParams.pageSize = 500
        const data = await downloadOrder(this.queryParams)
        this.$download.excel(data, `扣车订单_${new Date().getTime()}.xls`)
      } catch {
      } finally {
        this.exportLoading = false
      }
    },
    editInfo(data, type) {
      if (type == 2) {
        data.setMoney = data.setMoney2 * 100
      }
      updateInfo(data).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.editType = 0;
        this.editIdx = -1
        this.getList();
      });
    },
    editInfoFront(type, index) {
      this.editType = type
      this.editIdx = index
    },
    getBuckleName(id){
      return this.dictDataTree.find(item => item.id === id)?.buckleName || "其他"
    },
    openReturnCar(row){
      this.formData = {
        ...row
      }
      if (this.formData.setMoney){
        this.formData.setMoney = parseFloat(this.formData.setMoney / 100).toFixed(2)
      }
      if (this.formData.payMoney){
        this.formData.payMoney = parseFloat(this.formData.payMoney / 100).toFixed(2)
      }
      this.returnCar = true
    },
    // 还车
    async handleReturn(){
      if (this.formData.images){
        this.formData.images = this.formData.images.map(item => item.url).join(",")
      }
      try {
        await returnCar(this.formData)
        await this.handleChangeNode()
        await this.getTabList();
        this.returnCar = false
        this.$modal.msgSuccess("还车成功")
      }catch{}

    },
    // 删除
    handleDelete(row){
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除道路救援模块编号为"' + ids + '"的数据项？').then(function() {
        return delInfo(ids);
      }).then(() => {
        this.handleChangeNode()
        this.getTabList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 重新计算选择的节点
    async handleChangeNode(){
      // 如果他选择了节点
      if (this.chooseData){
        const res = await getBuckle(this.chooseData.id)
        const index = this.dictDataTree.find(item => item.id === res.data.id)
        this.dictDataTree[index] = res.data
        this.chooseData = res.data
        return;
      }
      // 否则全更新
      await this.getList()
    }
  }
}
</script>

<style scoped lang="scss">
.box-card {
  margin-bottom: 10px;
}

div {
  padding: 0;
  margin: 0 auto;
}

.app-container {
  display: flex;
  justify-content: space-between;
}

.left {
  width: 15%;
  margin-right: 1rem;
  padding: 1rem;
}

.right {
  width: 80%;
  padding-top: 1rem;
}

.left_top {
  color: #00afff;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji;
  font-size: 14px;
  padding-left: 5px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
::v-deep .el-form-item{
  margin-bottom: 22px;
}
</style>
