<template>
  <div class="app-container">
    <el-card style="height: 850px">
      <div style="margin-top: 7px; margin-bottom: 7px">
        <el-input v-model="consignee" style="width: 100px" size="small" clearable placeholder="收货人"/>
        <el-input v-model="orderValue" style="width: 200px" size="small" clearable placeholder="买方/订单号"/>
        <el-input v-model="logistics" style="width: 150px" size="small" clearable placeholder="物流单号"/>
        <span style="font-size: 13px;color: black">发货日期</span>
        <el-date-picker
          v-model="dateRange"
          size="small"
          type="daterange"
          align="center"
          style="width: 240px;"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          range-separator="～"
          clearable
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="pageCurrent = 1;pageSize = 100;searchTable()"/>
        <el-select v-model="deliveryStateValue" style="width:100px;margin-left: 10px" placeholder="发货状态" size="small" filterable clearable @change="pageCurrent = 1;pageSize = 100;searchTable()">
          <el-option
            v-for="item in deliveryState"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <el-button icon="el-icon-search" type="primary" plain size="small" style="margin-left: 10px" @click="pageCurrent = 1;pageSize = 100;searchTable()">查询</el-button>
      </div>
      <el-col style="margin-top: 10px;width: 891px">
        <el-table
          v-loading="loading"
          ref="table"
          :data="tableData"
          :summary-method="getSummaries"
          highlight-current-row
          show-summary
          border
          stripe
          size="small"
          style="width: 891px"
          height="740px"
          @row-click="searchTable1">
          <el-table-column :width="setColumnWidth('状态')" label="发货状态" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.发货状态==='未审核'" type="info" size="small" style="margin: 0px">未审核</el-tag>
              <el-tag v-if="scope.row.发货状态==='待审核'" type="primary" size="small" style="margin: 0px">待审核</el-tag>
              <el-tag v-if="scope.row.发货状态==='已审核'" type="warning" size="small" style="margin: 0px">已审核</el-tag>
              <el-tag v-if="scope.row.发货状态==='已发货'" type="success" size="small" style="margin: 0px">已发货</el-tag>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="发货单号" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.发货单号 }}
            </template>
          </el-table-column>
          <el-table-column width="87px" label="发货日期" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.发货日期 }}
            </template>
          </el-table-column>
          <el-table-column width="60px" label="收货人" align="center">
            <template slot-scope="scope">
              {{ scope.row.收货人 }}
            </template>
          </el-table-column>
          <el-table-column label="收货地址" align="center">
            <template slot-scope="scope">
              {{ scope.row.收货地址 }}
            </template>
          </el-table-column>
          <el-table-column width="102px" label="物流单号" align="center">
            <template slot-scope="scope">
              {{ scope.row.物流单号 }}
            </template>
          </el-table-column>
          <el-table-column width="87px" label="发货金额" align="center" prop="发货金额">
            <template slot-scope="scope">
              {{ Number(scope.row.发货金额).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column width="90px" label="发货备注" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              {{ scope.row.发货备注 }}
            </template>
          </el-table-column>
          <el-table-column width="117px" label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-top" size="mini" @click="uploadPicture(scope.row)">照片</el-button>
              <el-button v-show="Number(token)===8 || Number(token)===2" :disabled="scope.row.发货状态==='已发货'" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"/>
              <el-button type="text" icon="el-icon-edit" size="mini" @click="handleEdit(scope.row)"/>
              <el-button size="mini" type="text" icon="el-icon-picture-outline" @click="handlePicture(scope.row)"/>
              <el-tooltip :open-delay="500" effect="dark" content="退回发货单" placement="top">
                <el-button :disabled="scope.row.发货状态==='未确认'" type="text" icon="el-icon-back" @click="confirmReturn(scope.row)"/>
              </el-tooltip>
              <el-button :disabled="scope.row.审核状态 > 0" size="mini" type="text" @click="review(scope.row)">审核</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block" style="margin-top: 10px;">
          <el-pagination
            :current-page="pageCurrent"
            :page-sizes="[10, 20, 30, 40, 100]"
            :page-size="pageSize"
            :total="total"
            :pager-count="5"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChanges"
            @current-change="handleCurrentChanges"/>
        </div>
      </el-col>
      <el-col style="margin-top: 10px;margin-left: 20px;width: 751px">
        <el-table ref="table1" :data="tableData1" :header-cell-style="{background: '#2283D4',color: 'white'}" highlight-current-row border stripe size="small" style="width: 751px" height="740px">
          <el-table-column :width="setColumnWidth('序号')" label="序号" type="index" align="center"/>
          <el-table-column :width="setColumnWidth('订单号')" label="订单号" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.订单号 }}
            </template>
          </el-table-column>
          <el-table-column label="买方名称" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.买方名称 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('产品名称')" label="产品名称" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.产品名称 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('数量')" label="发货数量" align="center" prop="发货数量">
            <template slot-scope="scope">
              {{ scope.row.发货数量 ? scope.row.发货数量 : scope.row.查询实际发量 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('单价')" label="单价" align="center" prop="单价">
            <template slot-scope="scope">
              {{ Number(scope.row.单价).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column width="110px" label="金额" align="center" prop="金额">
            <template slot-scope="scope">
              {{ Number((scope.row.发货数量 ? scope.row.发货数量 : scope.row.查询实际发量) * scope.row.单价).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('数量')" label="订单数" align="center" prop="订单数">
            <template slot-scope="scope">
              {{ scope.row.订单数 }}
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-card>
    <el-dialog v-el-drag-dialog :visible.sync="dialogFormVisible" title="图片" center style="" width="600px">
      <el-image v-for="url in urls" :key="url" :src="url" :preview-src-list="urls" lazy style="width: 500px; height: 500px"/>
    </el-dialog>
    <el-dialog v-el-drag-dialog :visible.sync="dialogFormVisible1" title="编辑发货信息" center width="360px">
      <el-form ref="form" :model="form" :rules="rules" label-position="center" label-width="100px" class="demo-ruleForm">
        <el-form-item label="物流单号" prop="物流单号">
          <el-input v-model="form.物流单号" style="width:200px;" placeholder="物流单号" size="small" clearable/>
        </el-form-item>
        <el-form-item label="收货人" prop="收货人">
          <el-input v-model="form.收货人" style="width:200px;" placeholder="收货人" size="small" clearable/>
        </el-form-item>
        <el-form-item label="收货地址" prop="收货地址">
          <el-input v-model="form.收货地址" :rows="4" type="textarea" style="width:200px;" placeholder="收货地址" size="small" clearable/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff('form')">取消</el-button>
        <el-button type="distribution" size="small" @click="submitUpdate('form')">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-el-drag-dialog :visible.sync="dialogFormVisible2" title="上传图片" center width="320px">
      <el-upload
        id="invoiceScan"
        ref="upload"
        :multiple="true"
        :auto-upload="false"
        :on-success="uploadSuccess"
        :on-exceed="warningExceed"
        :limit="limit"
        :data="Data"
        :action="upload"
        style="margin-left: 60px"
        list-type="picture-card">
        <i class="el-icon-plus"/>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible2=false">取消</el-button>
        <el-button :loading="uploadSaving" type="distribution" size="small" @click="submit2('form')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { url, MESUploadFileNew, MESDownloadFileNew, MESUploadFileNew_BasePath } from '@/utils/request'
import axios from 'axios'
export default {
  data() {
    return {
      Data: {},
      limit: 1000,
      upload: url,
      uploadSaving: false,
      uploadFileTotal: 0,
      uploadFileFinished: 0,
      uploadFileFailed: 0,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      listValue: '',
      form: {
        物流单号: '',
        收货人: '',
        收货地址: ''
      },
      rules: {
        物流单号: [{ required: true, message: '请输入物流单号', trigger: 'blur' }],
        收货人: [{ required: true, message: '请输入收货人', trigger: 'blur' }],
        收货地址: [{ required: true, message: '请输入收货地址', trigger: 'change' }]
      },
      dialogFormVisible: false,
      urls: [],
      consignee: '', // 收货人
      logistics: '', // 物流单号
      orderValue: '', // 订单号
      dateRange: '', // 发货日期
      deliveryStateValue: '', // 发货状态
      deliveryState: [{
        value: 0,
        label: '未确认'
      }, {
        value: 1,
        label: '已发货'
      }], // 发货状态数组
      loading: false, // 数据加载
      total: 0, // 分页总数
      tableData: [], // 订单信息表
      tableData1: [], // 产品信息表
      pageCurrent: 1, // 分页当前页
      pageSize: 100, // 分页每页显示条数
      deliveryMxValue: [],
      deliveryNum: [],
      orderName: '', // 排序列名
      order: '' // 排序方式
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token'
    ])
  },
  updated() {
    this.$nextTick(() => {
      this.$refs['table'].doLayout()
      this.$refs['table1'].doLayout()
    })
  },
  created() {
    this.searchTable()
  },
  methods: {
    review(row) {
      this.$confirm('是否通知审核?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param1 = []
        param1[0] = ['发货单流水号', row.发货单流水号]
        var Data1 = this.CreateData('12', '发货查询_发货单_通知审核', param1)
        this.ExecDatabase(Data1).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('通知成功')
            this.searchTable()
          } else {
            this.$message.error('通知失败')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    warningExceed() {
      this.$message.error('仅可上传五张照片')
    },
    uploadSuccess(res, file) { // 上传成功回调
      // 生成文件保存路径: 基础路径/DeliveryRecord/年月日时分秒毫秒.后缀
      const now = new Date()
      const timestamp = now.getFullYear().toString() +
        (now.getMonth() + 1).toString().padStart(2, '0') +
        now.getDate().toString().padStart(2, '0') +
        now.getHours().toString().padStart(2, '0') +
        now.getMinutes().toString().padStart(2, '0') +
        now.getSeconds().toString().padStart(2, '0') +
        now.getMilliseconds().toString().padStart(3, '0')
      const suffix = file.name.split('.').pop() || 'jpg'
      const lastDotIndex = file.name.lastIndexOf('.')
      const fileName = lastDotIndex > -1 ? file.name.slice(0, lastDotIndex) : file.name
      const sqlFileName = fileName.replace(/'/g, "''")
      const sqlSuffix = suffix.replace(/'/g, "''")
      const uniqueCode = Math.random().toString(36).slice(2, 8)
      const savePath = MESUploadFileNew_BasePath + '\\DeliveryRecord\\' + timestamp + '-' + this.listValue + '-' + uniqueCode + '.' + suffix

      // 构造SQL语句：清空文件内容，更新文件路径
      const sqlStatement = `update 发货管理_发货单_图片 set 文件内容 = NULL, 文件路径 = N'${savePath}' where id = (select top 1 id from 发货管理_发货单_图片 where 发货单流水号 = ${this.listValue} and 文件名称 = N'${sqlFileName}' and 文件后缀 = N'${sqlSuffix}' and 文件路径 is null order by 操作时间 desc, id desc); IF @@ROWCOUNT <> 1 RAISERROR(N'图片路径回填失败', 16, 1)`

      // 调用新接口保存文件到磁盘
      const formData = new FormData()
      formData.append('file', file.raw)
      formData.append('savePath', savePath)
      formData.append('sqlStatement', sqlStatement)

      axios.post(MESUploadFileNew, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(response => {
        if (response.data && response.data[0] && response.data[0].result === '1') {
          console.log('文件保存成功:', savePath)
        } else {
          this.uploadFileFailed++
          console.error('文件保存失败:', response.data)
        }
      }).catch(err => {
        this.uploadFileFailed++
        console.error('文件保存异常:', err)
      }).finally(() => {
        this.uploadFileFinished++
        if (this.uploadFileFinished >= this.uploadFileTotal) {
          this.uploadSaving = false
          if (this.uploadFileFailed === 0) {
            this.$message.success('图片上传成功')
            this.dialogFormVisible2 = false
            this.$refs.upload.clearFiles()
            this.searchTable()
          } else {
            this.$message.error('部分图片上传失败，请重新上传失败图片')
          }
        }
      })
    },
    submit2() {
      if (!this.$refs.upload || this.$refs.upload.uploadFiles.length === 0) {
        this.$message.warning('请选择图片')
        return
      }
      this.uploadSaving = true
      this.uploadFileTotal = this.$refs.upload.uploadFiles.length
      this.uploadFileFinished = 0
      this.uploadFileFailed = 0
      var param = []
      param[0] = ['发货单流水号', this.listValue]
      param[1] = ['文件名称', '']
      param[2] = ['文件后缀', '']
      param[3] = ['文件内容', null]
      var Data1 = this.CreateData('15', '发货管理_发货单_上传图片', param)
      this.Data.param = Data1
      this.$refs.upload.submit()
    },
    uploadPicture(row) {
      this.dialogFormVisible2 = true
      this.listValue = row.发货单流水号
    },
    submitUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param1 = []
          param1[0] = ['发货单流水号', this.form.发货单流水号]
          param1[1] = ['物流单号', this.form.物流单号]
          param1[2] = ['收货人', this.form.收货人]
          param1[3] = ['收货地址', this.form.收货地址]
          var Data1 = this.CreateData('12', '发货查询_发货单_编辑', param1)
          this.ExecDatabase(Data1).then(response => {
            if (response.data[0].result === '1') {
              this.$message.success('编辑成功')
              this.searchTable()
              this.dialogFormVisible1 = false
            } else {
              this.$message.error('编辑失败')
            }
          })
        }
      })
    },
    callOff(formName) {
      this.form.物流单号 = ''
      this.form.收货人 = ''
      this.form.收货地址 = ''
      this.dialogFormVisible1 = false
      this.$refs[formName].resetFields()
    },
    handleEdit(row) {
      if (this.$refs['form'] !== undefined) {
        this.$refs['form'].resetFields()
      }
      this.title = '编辑物料'
      this.form.物流单号 = row.物流单号
      this.form.发货单流水号 = row.发货单流水号
      this.form.收货人 = row.收货人
      this.form.收货地址 = row.收货地址
      this.dialogFormVisible1 = true
    },
    searchTable() {
      console.log(this.token)
      this.tableData1 = []
      let consignee_check, dateRange_check, deliveryStateValue_check, logistics_check, orderValue_check
      this.consignee ? consignee_check = 1 : consignee_check = 0
      this.logistics ? logistics_check = 1 : logistics_check = 0
      this.orderValue ? orderValue_check = 1 : orderValue_check = 0
      this.dateRange ? dateRange_check = 1 : (dateRange_check = 0, this.dateRange = '')
      if (this.deliveryStateValue === 0) {
        deliveryStateValue_check = 1
      } else if (this.deliveryStateValue) {
        deliveryStateValue_check = 1
      } else {
        deliveryStateValue_check = 0
      }
      var param = []
      param[0] = ['收货人_check', consignee_check]
      param[1] = ['收货人', this.consignee]
      param[2] = ['发货状态_check', deliveryStateValue_check]
      param[3] = ['发货状态', this.deliveryStateValue]
      param[4] = ['订单号_check', orderValue_check]
      param[5] = ['订单号', this.orderValue]
      param[6] = ['物流单号_check', logistics_check]
      param[7] = ['物流单号', this.logistics]
      param[8] = ['时间_check', dateRange_check]
      param[9] = ['开始时间', this.dateRange[0]]
      param[10] = ['结束时间', this.dateRange[1]]
      param[11] = ['排序名称', '']
      param[12] = ['排序方式', '']
      var Data = this.CreateData('11', '产品发货_发货单_查询数据', param, this.pageSize, this.pageCurrent)
      this.ExecDatabase(Data).then(response => {
        this.tableData = response.data.rows
        this.total = response.data.total
      })
    },
    searchTable1(row) {
      var param = []
      param[0] = ['发货单流水号', row.发货单流水号]
      param[1] = ['已发', 0]
      var Data = this.CreateData('11', '产品发货_发货单明细_查询数据新', param)
      this.ExecDatabase(Data).then(response => {
        this.tableData1 = response.data
      })
    },
    handlePicture(row) {
      this.dialogFormVisible = true
      this.urls = []
      var param = []
      param[0] = ['发货单流水号', row.发货单流水号]
      var Data = this.CreateData('11', '发货单_图片_查询数据', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          const item = response.data[i]
          // 优先使用文件路径（新方式），否则使用数据库内容（旧方式）
          if (item.文件路径) {
            // 从文件系统读取
            axios.get(MESDownloadFileNew, {
              params: { filePath: item.文件路径 }
            }).then(res => {
              if (res.data && res.data[0] && res.data[0].文件内容) {
                this.urls.push('data:image/png;base64,' + res.data[0].文件内容)
              }
            }).catch(err => {
              console.error('图片加载失败:', err)
            })
          } else if (item.文件内容 !== null) {
            // 兼容旧数据：直接使用数据库中的base64
            this.urls.push('data:image/png;base64,' + item.文件内容)
          }
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['发货单流水号', row.发货单流水号]
        var Data = this.CreateData('12', '产品发货_发货单_删除', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('删除成功')
            this.searchTable()
          } else {
            this.$message.error('删除失败')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    confirmReturn(row) {
      this.$confirm('是否退回?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deliveryMxValue = []
        this.deliveryNum = []
        for (let i = 0; i < this.tableData1.length; i++) {
          this.deliveryMxValue.push(this.tableData1[i].发货单明细流水号)
          if (isNaN(this.tableData1[i].发货数量) === false) {
            if (this.tableData1[i].发货数量 !== '' && this.tableData1[i].发货数量 !== '0' && this.tableData1[i].发货数量 !== null) {
              this.deliveryNum.push(this.tableData1[i].发货数量)
            } else {
              this.$message.error('已发数量不能为0或空')
              break
            }
          } else {
            this.$message.error('已发数量必须为数值')
            break
          }
        }
        var param = []
        param[0] = ['发货单流水号', row.发货单流水号]
        param[1] = ['发货单明细流水号组', this.deliveryMxValue]
        param[2] = ['已发数量组', this.deliveryNum]
        var Data = this.CreateData('12', '产品查询_发货单_退回发货', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('退回成功')
            this.searchTable()
            // this.searchTable1()
            this.tableData1 = []
          } else {
            this.$message.success('退回失败')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (index === 6) {
          const values = data.map(item => Number(item['发货金额']))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(2)
          } else {
            sums[index] = 'N/A'
          }
        }
      })
      return sums
    },
    handleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChanges(val) {
      this.pageCurrent = val
      this.searchTable()
    }
  }
}
</script>
<style>
  .ziduan {
    width: 50px!important;
  }
</style>
