//副产品统计报表
<template>
  <div class="purchasFuelNewMonitor">
    <div class="items">
      <el-form :inline="true" style="margin-top :5px">
        <el-form-item>
          <el-select
            v-model="screen3"
            placeholder="请选择查询的时间类型"
            clearable
            style="width:90px"
          >
            <el-option
              v-for="item in options3"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-date-picker
            v-model="startTime"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
          <span>至</span>
          <el-date-picker
            v-model="endTime"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
          <el-select
            v-model="condition1"
            placeholder="请选择筛选条件"
            style="width:150px"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            placeholder="请输入内容"
            v-model="input1"
            style="width:200px"
            clearable
          >
          </el-input>
          <el-select
            v-model="condition2"
            placeholder="请选择筛选条件"
            style="width:150px"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            placeholder="请输入内容"
            v-model="input2"
            style="width:200px"
            clearable
          >
          </el-input>
          <el-button type="primary" class="btn" @click="onclick">
            <i class="el-icon-search"></i>
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportData()"
            ><i class="el-icon-download"></i>Excel</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="refresh">
            <i class="el-icon-refresh"></i>
          </el-button>
        </el-form-item>
        <el-form-item>
          <span>合计净重：</span>
          <el-input
            v-model="totalNumber"
            :disabled="true"
            style="width: 100px;"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <span>合计车数：</span>
          <el-input
            v-model="totalCapacity"
            :disabled="true"
            style="width: 50px;"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="dealWithOverWeight">
            超重出厂
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="openReceive()">
            <i class="el-icon-document"></i>签收抵达</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="checkTrans()">
            <i class="el-icon-truck"></i>轨迹
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <dilTable
        ref="excelDom"
        v-bind.sync="option"
        :isHeigth="isHeigth"
        :shiyHeigth="shiyHeigth"
        :isKuang="isKuang"
        @func="func"
        highlight-current-row
        @radio-change="selectOne"
        :pageSize="pageSize"
      >
        <el-table-column
          label="抵达地址"
          width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="showPic(scope.row.arrivalPhoto)"
              >{{ scope.row.arrivalAddress }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          label="签收地址"
          width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="showPic(scope.row.receiptPhoto)"
              >{{ scope.row.receiptAddress }}</el-button
            >
          </template>
        </el-table-column>
      </dilTable>
    </div>
    <div style="height: 100%">
      <vxe-modal
        width="1237"
        height="731"
        v-model="value7"
        show-zoom
        resize
        title="轨迹查询"
      >
        <template #default>
          <PathView v-bind.sync="pathOption"></PathView>
        </template>
      </vxe-modal>
    </div>
    <el-dialog :visible.sync="disvisiable">
      <div class="admin2">
        <div class="carrier from">
          <el-form :inline="true" class="demo-form-inline" label-width="80px">
            <el-form-item label="车牌号:">
              <el-autocomplete
                class="inline-input"
                v-model="capacityName"
                :fetch-suggestions="querySearchCapacity"
                placeholder="车牌号"
                :trigger-on-focus="false"
                @select="handleSelectCapacity"
              >
                <template slot-scope="{ item }">
                  <div class="name">{{ item.capacityNumber }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-form>
        </div>
        <div class="poundNo from">
          <span class="text">运输订单号:</span>
          <el-input v-model="orderNumber" disabled></el-input>
        </div>
        <div class="button_box">
          <el-button type="primary" @click="updateCanwork" :disabled="disabled"
            >确认</el-button
          >
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="抵达签收"
      :visible.sync="arrivalReceiving"
      :before-close="closeUpload"
    >
      <el-form style="margin-left:20%">
        <el-form-item label="车牌号码">
          <el-input
            v-model="capacityNumber"
            disabled
            style="width:300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="签收地址">
          <el-input
            v-model="location"
            style="width:400px"
            :disabled="orgCode != 'wuliuyunshubu'"
          ></el-input>
        </el-form-item>
        <el-form-item label="抵达时间">
          <el-date-picker
            v-model="arrivalTime"
            type="datetime"
            :disabled="orgCode != 'wuliuyunshubu'"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="签收时间">
          <el-date-picker
            v-model="receiptTime"
            type="datetime"
            :disabled="orgCode != 'wuliuyunshubu'"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="抵达图片（车头、满货箱）" style="">
          <el-upload
            ref="arrival"
            list-type="picture-card"
            :file-list="arriavlList"
            action="/api/v1/otms/addtmstruckArrivalResult"
            :limit="12"
            :on-change="fileChange1"
            :on-remove="fileChange1"
            :on-preview="handlePictureCardPreview"
            :on-exceed="exceed"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF"
            :auto-upload="false"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="签收图片（空货箱、质保书、签收单）">
          <el-upload
            ref="receive"
            list-type="picture-card"
            :file-list="receiveList"
            action="null"
            :limit="11"
            :on-change="fileChange2"
            :on-remove="fileChange2"
            :on-preview="handlePictureCardPreview"
            :on-exceed="exceed"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF"
            :auto-upload="false"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        @click="arrivalAndReceive"
        :loading="isLoading"
        style="margin-left:40%"
        >确定</el-button
      >
    </el-dialog>
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="80%">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <el-dialog title="图片查看" :visible.sync="dialogVisible2" width="80%">
      <img
        width="100%"
        v-for="item in picList"
        :src="item"
        :key="item"
        alt=""
      />
    </el-dialog>
  </div>
</template>

<script>
import { sjTime } from '@/utils/sharedJsFile'
import { getCookie } from '@/utils/util.js'
import PathView from './mapTest.vue'
import currentLocation from './currentLocation.vue'
export default {
  components: {
    PathView,
    currentLocation
  },
  data() {
    return {
      condition1: null,
      condition2: null,
      input1: null,
      input2: null,
      options: [
        {
          label: '车牌号',
          value: 'capacityNumber'
        },
        {
          label: '收货单位',
          value: 'receivName'
        },
        {
          label: '物资名称/备注',
          value: 'remark'
        },
        {
          label: '装货地点',
          value: 'wareHouse'
        }
      ],
      screen3: '计毛时间',
      options3: [
        {
          label: '计毛时间',
          value: '计毛时间'
        },
        {
          label: '进厂时间',
          value: '进厂时间'
        }
      ],
      orderNumber: null,
      orderId: null,
      disabled: false,
      capacityName: null,
      disvisiable: false,
      shiyHeigth: 140,
      isHeigth: true,
      pageSize: 100,
      isKuang: false,
      option: {
        requestUrl: '',
        selectionType: 'radio',
        requestQuery: null
      },
      startTime: null,
      endTime: null,
      //合计净重
      totalNumber: 0,
      //合计车数
      totalCapacity: 0,
      tableTitle: '销售统计报表',
      inputMaterial: null,
      inputReceiveName: null,
      wareHouse: null,
      //抵达签收
      selection: null,
      orgCode: null,
      location: null,
      capacityNumber: null,
      arrivalReceiving: false,
      arriavlList: [],
      receiveList: [],
      fileListArrival: [],
      fileListReceive: [],
      dialogImageUrl: '',
      dialogVisible: false,
      picList: [],
      dialogVisible2: false,
      isLoading: false,
      arrivalTime: null,
      receiptTime: null,
      dialogFormVisible: false,
      //轨迹
      value7: false,
      pathOption: {
        orderNumber: '',
        capacityNumber: '',
        startPointName: '',
        endPointName: '',
        statusCode: '位置'
      }
    }
  },
  created() {
    //初始化表头
    if (getCookie('orgCode') == 'chengyunshang') {
      this.option.requestUrl =
        '/api/v1/tms/getAllSaleReport?apiId=526&startTime=null&endTime=null&orderType=2&shipperId=1&carrierSsoId=' +
        getCookie('userId') +
        '&i=' +
        new Date()
    } else {
      this.option.requestUrl =
        '/api/v1/tms/getAllSaleReport?apiId=526&startTime=null&endTime=null&orderType=2&shipperId=1&carrierSsoId=' +
        null +
        '&i=' +
        new Date()
    }
    //时间段初始化
    const start = new Date(new Date(new Date().toLocaleDateString()).getTime())
    var startTime = this.dataFormat(sjTime(start))
    var endTime = this.dataFormat(sjTime(new Date()))
    this.tableTitle = startTime + ' 至 ' + endTime
    this.orgCode = getCookie('orgCode')
    console.log(this.orgCode)
  },
  methods: {
    //选中
    selectOne(selection) {
      console.log('selection', selection)
      this.selection = selection
    },
    //抵达签收
    openReceive() {
      if (!this.selection) {
        this.$message.warning('请选择需要补录的实绩')
        return
      }
      let row = this.selection
      if (!row.resultOutGateTime) {
        this.$message.warning('该车未出厂，不允许签收')
        return
      }
      if (row.arrivalAddress) {
        //优先获取抵达地址
        this.location = row.arrivalAddress
      } else {
        //其次获取车辆定位
        this.axios
          .get(
            '/api/v1/otms/getCurrentLocation?capcityNumber=' +
              row.capacityNumber
          )
          .then(res => {
            if (
              res.data.status == 'succeed' &&
              res.data.data.result.status != 1001
            ) {
              this.location = res.data.data.result.adr
            } else {
              this.location = null
              // this.$message.warning('获取不到车辆定位！请联系销售公司上传！')
            }
          })
      }
      this.orderNumber = row.orderNumber
      this.capacityNumber = row.capacityNumber
      this.arrivalTime = row.arrivalTime
      this.receiptTime = row.receiptTime
      this.arrivalReceiving = true
      //抵达图片
      this.axios
        .post('/api/v1/otms/getArrivalPhoto?orderNumber=' + row.orderNumber)
        .then(res => {
          console.log('arrivalPhoto:', res)
          if (res.data) {
            this.arriavlList = []
            res.data.forEach((e, index) => {
              creatImageFile(e, 'file1-' + index).then(res => {
                this.arriavlList.push({
                  name: 'file' + index,
                  raw: res,
                  url: e
                })
              })
            })
            this.fileListArrival = this.arriavlList
          }
        })
      //签收图片
      this.axios
        .post(
          '/api/v1/otms/getReceivingPhotoByUrl?orderNumber=' + row.orderNumber
        )
        .then(res => {
          console.log('ReceivingPhoto:', res)
          if (res.data) {
            this.receiveList = []
            res.data.forEach((e, index) => {
              creatImageFile(e, 'file2-' + index).then(res => {
                this.receiveList.push({
                  name: 'file' + index,
                  raw: res,
                  url: e
                })
              })
            })
            this.fileListReceive = this.receiveList
          }
        })
    },
    arrivalAndReceive() {
      if (!this.location) {
        this.$message.warning(
          '签收地址必须取车辆定位！若取不到请联系销售公司上传！'
        )
        return
      }
      if (this.fileListArrival.length < 3) {
        this.$message.warning('抵达图至少三张')
        return
      }
      if (this.fileListReceive.length < 2) {
        this.$message.warning('签收图最少两张')
        return
      }
      this.isLoading = true
      //上传抵达
      let formData = new window.FormData()
      this.fileListArrival.forEach((item, index) => {
        formData.append('file' + index, item.raw)
      })
      formData.append('orderNumber', this.orderNumber)
      formData.append('resultArrivalAddress', this.location)
      if (this.arrivalTime) {
        formData.append('arrivalTime', sjTime(this.arrivalTime))
      }
      let options = {
        // 设置axios的参数
        url: '/api/v1/otms/addtmstruckArrivalResult',
        data: formData,
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.axios(options).then(res => {
        console.log('arrivalRes:', res)
        //上传签收
        let formData = new window.FormData()
        let request = ''
        this.fileListReceive.forEach((item, index) => {
          formData.append('file' + index, item.raw)
        })
        formData.append('orderNumber', this.orderNumber)
        formData.append('resultArrivalAddress', this.location)
        if (this.receiptTime) {
          formData.append('receiptTime', sjTime(this.receiptTime))
        }
        formData.append('num', request.length)
        let options = {
          url: '/api/v1/otms/addTmstruckReceiptResultForWeb',
          data: formData,
          method: 'post',
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        this.axios(options).then(res => {
          console.log('receiveRes:', res)
          this.$message.success('上传成功！')
          this.selection.arrivalAddress = this.location
          this.closeUpload()
          // this.refresh()
        })
      })
    },
    fileChange1(file, fileList) {
      this.fileListArrival = fileList
    },
    fileChange2(file, fileList) {
      this.fileListReceive = fileList
    },
    fileChange3(file, fileList) {
      this.remarkPicList = fileList
    },
    exceed() {
      this.$message.warning('超出上传数量!')
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    closeUpload() {
      this.location = null
      this.arrivalTime = null
      this.receiptTime = null
      this.arrivalReceiving = false
      this.isLoading = false
      this.$refs.arrival.clearFiles()
      this.$refs.receive.clearFiles()
    },
    showPic(urls) {
      //获取图片到本地
      this.axios.post('/api/v1/uc/getPicture', { urls: urls }).then(res => {
        console.log(res)
        if (res.data) {
          // let remarkPicList = []
          // res.data.forEach((e, index) => {
          //   creatImageFile(e, 'file2-' + index).then(res => {
          //     remarkPicList.push({
          //       name: 'file' + index,
          //       raw: res,
          //       url: e
          //     })
          //   })
          // })
          this.picList = res.data
        } else {
          this.picList = []
        }
        this.dialogVisible2 = true
      })
    },
    //轨迹
    checkTrans() {
      let row = this.selection
      if (!this.selection) {
        this.$message.error('请点击需要查看轨迹的行！')
        return
      }
      if (row.resultOutGateTime == null) {
        this.$message.error('该车还未出厂,暂无轨迹')
        return
      }
      let that = this
      that.axios
        .post('/api/v1/otms/fullPath?orderNumber=' + row.orderNumber)
        .then(res => {
          console.log(res.data)
          if (res.data.data == '-1') {
            this.$message.error('运输订单未关闭的自提车辆无权查看!')
          } else if (res.data.data.startAndEndRoutes != null) {
            that.pathOption.orderNumber = row.orderNumber
            that.pathOption.capacityNumber = row.capacityNumber
            that.pathOption.startPointName = '达钢集团小东门'
            that.pathOption.endPointName = row.receiptAddress
            that.value7 = true
            if (row.orderStatus == '已完成') {
              that.pathOption.statusCode = '位置'
            } else {
              that.pathOption.statusCode = '当前位置'
            }
          } else {
            this.$message.error('车辆没有开启GPS')
          }
        })
    },
    // getReceiveName() {
    //   if (this.inputReceiveName != null) {
    //     if (getCookie("orgCode") == "chengyunshang") {
    //       this.option.requestUrl =
    //         "/api/v1/tms/getAllSaleReport?apiId=423&startTime=null&endTime=null&orderType=2&shipperId=2&carrierSsoId=" +
    //         getCookie("userId") +
    //         "&i=" +
    //         new Date() +
    //         "&receiveName=" +
    //         this.inputReceiveName;
    //     } else {
    //       this.option.requestUrl =
    //         "/api/v1/tms/getAllSaleReport?apiId=423&startTime=null&endTime=null&orderType=2&shipperId=2&carrierSsoId=" +
    //         null +
    //         "&i=" +
    //         new Date() +
    //         "&receiveName=" +
    //         this.inputReceiveName;
    //     }
    //   } else {
    //     if (getCookie("orgCode") == "chengyunshang") {
    //       this.option.requestUrl =
    //         "/api/v1/tms/getAllSaleReport?apiId=423&startTime=null&endTime=null&orderType=2&shipperId=2&carrierSsoId=" +
    //         getCookie("userId") +
    //         "&i=" +
    //         new Date();
    //     } else {
    //       this.option.requestUrl =
    //         "/api/v1/tms/getAllSaleReport?apiId=423&startTime=null&endTime=null&orderType=2&shipperId=2&carrierSsoId=" +
    //         null +
    //         "&i=" +
    //         new Date();
    //     }
    //   }
    // },
    dealWithOverWeight() {
      this.disvisiable = true
    },
    //以下是运力边输边查搜索
    querySearchCapacity(queryString, cb) {
      if (queryString.length < 3) {
        return
      }
      this.axios
        .get('/api/v1/uc/getCapacityNumber?index=' + queryString)
        .then(res => {
          if (res.data.code == '200') {
            var restaurantsCarrier = res.data.data
            console.log(restaurantsCarrier, 'restaurantsCarrier')
            var results = queryString
              ? restaurantsCarrier.filter(this.createFilterCarrier(queryString))
              : restaurantsCarrier
            // 调用 callback 返回建议列表的数据
            cb(results)
          }
        })
    },
    createFilterCarrier(queryString) {
      return restaurantsCarrier => {
        return (
          restaurantsCarrier.capacityNumber
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) > -1
        )
      }
    },
    updateCanwork() {
      console.log(this.orderNumber)
      this.axios
        .post('/api/v1/bp/updateOrderCanWork?orderNumber=' + this.orderNumber)
        .then(res => {
          this.$message.success('修改成功')
          this.$router.go(0)
        })
    },
    //运力弹出层
    handleSelectCapacity(item) {
      this.capacityId = item.capacityId
      this.capacityName = item.capacityNumber
      this.axios
        .get('/api/v1/uc/getOrderNumber?capacityId=' + this.capacityId)
        .then(res => {
          if (res.data.code == '200') {
            this.orderId = res.data.data.orderId
            this.orderNumber = res.data.data.orderNumber
            this.axios
              .get('/api/v1/uc/getMaterialIdByOrderId?orderId=' + this.orderId)
              .then(res => {
                if (res.data.code == '200') {
                  this.materialList = res.data.data
                }
              })
          }
        })
    },
    refresh() {
      this.$router.go(0)
    },
    func(res) {
      console.log(res)
      var resultNetWeightTotal = 0
      res.list.forEach(e => {
        resultNetWeightTotal = resultNetWeightTotal + e.resultNetWeight
      })
      this.totalNumber = resultNetWeightTotal.toFixed(2) + ' t'
      this.totalCapacity = res.total
      //获取总记录条数作为合计车数
      // this.totalCapacity = res.total;
      this.isKuang = false
    },
    onclick() {
      let startTime = null
      let endTime = null
      let isEnfactoryFlag = null
      if (this.screen3 == '进厂时间') {
        isEnfactoryFlag = 1
      }
      let requestQuery = {}
      if (!this.condition1) {
        requestQuery['remarkNo'] = this.input1 + ''
      }
      if (!this.condition2) {
        requestQuery['remarkNo2'] = this.input2 + ''
      }
      requestQuery[this.condition1] = this.input1 + ''
      requestQuery[this.condition2] = this.input2 + ''
      requestQuery.isEnfactoryFlag = isEnfactoryFlag
      this.option.requestQuery = requestQuery
      if (this.startTime && this.endTime) {
        startTime = sjTime(this.startTime)
        endTime = sjTime(this.endTime)
        //修改报表名称
        this.tableTitle =
          this.dataFormat(startTime) + ' 至 ' + this.dataFormat(endTime)
        //加上时间重置表头
        if (getCookie('orgCode') == 'chengyunshang') {
          this.option.requestUrl =
            '/api/v1/tms/getAllSaleReport?apiId=526&startTime=' +
            startTime +
            '&endTime=' +
            endTime +
            '&orderType=2&shipperId=1' +
            '&carrierSsoId=' +
            getCookie('userId') +
            '&i=' +
            new Date() +
            '&isEnfactoryFlag=' +
            isEnfactoryFlag
        } else {
          this.option.requestUrl =
            '/api/v1/tms/getAllSaleReport?apiId=526&startTime=' +
            startTime +
            '&endTime=' +
            endTime +
            '&orderType=2&shipperId=1' +
            '&carrierSsoId=' +
            null +
            '&i=' +
            new Date() +
            '&isEnfactoryFlag=' +
            isEnfactoryFlag
        }
      } else {
        if (this.startTime) {
          startTime = sjTime(this.startTime)
        } else if (this.endTime) {
          endTime = sjTime(this.endTime)
        }
        //加上时间重置表头
        if (getCookie('orgCode') == 'chengyunshang') {
          this.option.requestUrl =
            '/api/v1/tms/getAllSaleReport?apiId=526&startTime=' +
            startTime +
            '&endTime=' +
            endTime +
            '&orderType=2&shipperId=1' +
            '&carrierSsoId=' +
            getCookie('userId') +
            '&i=' +
            new Date() +
            '&isEnfactoryFlag=' +
            isEnfactoryFlag
        } else {
          this.option.requestUrl =
            '/api/v1/tms/getAllSaleReport?apiId=526&startTime=' +
            startTime +
            '&endTime=' +
            endTime +
            '&orderType=2&shipperId=1' +
            '&carrierSsoId=' +
            null +
            '&i=' +
            new Date() +
            '&isEnfactoryFlag=' +
            isEnfactoryFlag
        }
      }
    },
    //格式化日期
    dataFormat(value) {
      let date = new Date(value)
      let y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? '0' + MM : MM
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let h = date.getHours()
      h = h < 10 ? '0' + h : h
      let m = date.getMinutes()
      m = m < 10 ? '0' + m : m
      let s = date.getSeconds()
      s = s < 10 ? '0' + s : s
      return y + '-' + MM + '-' + d + ' ' + h + '：' + m + '：' + s
    }
  }
}
</script>

<style lang="scss">
.purchasFuelNewMonitor {
  .items {
    margin-left: 20px;
    margin-top: 20px;
  }
  .table {
    margin-left: 20px;
    margin-top: 20px;
  }
}
</style>
