<template>
  <div class="app-container">
    <!--    <el-container style=" border: 1px solid #eee">-->
    <!--      <el-aside width="420px" style="background-color: rgb(238, 241, 246)">-->
    <el-row :gutter="20">
      <el-col :span="9">
        <div class="filter-container">
          <div style="margin: auto; left: 0; right: 0; top: 0; bottom: 0">
            <el-input size="mini" clearable v-model="search.keyWord" placeholder="关键字" style="width: 200px;"
                      class="filter-item" @keyup.enter.native="searchData"/>

            <el-date-picker
              size="mini"
              v-model="valueDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy - MM - dd "
              value-format="yyyy-MM-dd"
              :default-time="['00:00:00', '23:59:59']">
            </el-date-picker>

            <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
              搜索
            </el-button>

            <el-button size="mini" class="filter-item" type="primary" icon="el-icon-printer" @click="printSendBill">
              打印
            </el-button>
            <el-button size="mini" class="filter-item" type="primary" @click="getList">
              刷新
            </el-button>
          </div>
          <div class="rowHoverNone">
            <el-table
              :data="billTableData"
              v-loading="billListLoading"
              size="mini"
              ref="sendBillTable"
              @row-click="handleSendBillClickTableRow"
              row-key="id"
              border
              @selection-change="onTableSelectionChange"
              :row-style="customRowStyle"
              :row-class-name="rowClassName"
              style="margin-top: 10px">
              <el-table-column
                type="selection"
                width="30">
              </el-table-column>
              <el-table-column fixed label="操作" align="center" width="60px" class-name="small-padding fixed-width">
                <template slot-scope="{row}">
                  <el-button
                    size="mini"
                    type="info"
                    icon="el-icon-delete"
                    class="iconfont"
                    title="作废"
                    v-show="row.voidFlag === 0"
                    @click.stop="showDialogVoidSendBill(row)">
                  </el-button>
                </template>
              </el-table-column>
              <template v-for="column in billColumnNames">
                <el-table-column
                  :key="column.field"
                  :prop="column.field"
                  :label="column.name"
                  :width="column.width"
                  :formatter="columnFormatter"
                  show-overflow-tooltip>
                </el-table-column>
              </template>
            </el-table>
            <pagination
              v-show="listData.total>0"
              :total="listData.total"
              :page.sync="listData.page"
              :limit.sync="listData.pageSize"
              @pagination="getList"/>
          </div>

        </div>
      </el-col>
      <!--      </el-aside>-->
      <el-col :span="15">
        <!--      <el-main>-->
        <el-table
          :data="itemTableData"
          v-loading="itemListLoading"
          size="mini"
          ref="sendItemTable"
          row-key="id"
          border
          style="margin-top: 55px">
          <el-table-column fixed label="操作" align="center" width="120" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-button
                title="查看订单"
                @click.stop="openDetail(row)"
                type="primary"
                class="iconfont"
                icon="el-icon-view"
                size="mini">
              </el-button>
              <el-button
                size="mini"
                type="success"
                icon="el-icon-s-order"
                class="iconfont"
                title="发货反馈"
                v-show="row.voidFlag ===0 && row.chargeKind !== 2 && row.itemState === 5"
                @click.stop="showFeedbackDrawer(row)">
              </el-button>
            </template>
          </el-table-column>
          <template v-for="column in itemColumnNames">
            <el-table-column
              v-if="column.field ==='payKind'"
              :key="column.field"
              :prop="column.field"
              :label="column.name"
              show-overflow-tooltip
              :width="column.width">
              <template slot-scope="{row}">
                {{ getpayKind(row.payKind) }}
              </template>
            </el-table-column>
            <el-table-column
              v-else
              :key="column.field"
              :prop="column.field"
              :label="column.name"
              :width="column.width"
              :formatter="columnFormatter"
              show-overflow-tooltip>
            </el-table-column>
          </template>
        </el-table>
        <!--      </el-main>-->
      </el-col>
    </el-row>
    <!--    </el-container>-->

    <el-drawer
      title="发货反馈"
      ref="deliverFeedbackDrawer"
      :visible.sync="showDrawer"
      :before-close="drawerClose"
      direction="rtl"
      :destroy-on-close=true
      :show-close=false
      :wrapperClosable=false
      size="35%"
    >
      <div>
        <el-card v-if="feedbackItem" class="box-card" style="margin-bottom: 20px; margin-left: 20px">
          <div slot="header" class="clearfix">
            <span>{{ feedbackItem.referenceCode }}</span>
          </div>
          <div class="text item">
            产品类型: {{ feedbackItem.productName }}
          </div>
          <div class="text item">
            订单名称: {{ feedbackItem.orderName }}
          </div>
          <div class="text item">
            客户名称: {{ feedbackItem.clientName }}
          </div>
          <div class="text item">
            订单金额: {{ feedbackItem.orderMoneyTotal }}
          </div>
          <div class="text item">
            收款方式: {{ feedbackItem.payKind }}
          </div>
        </el-card>
        <el-form :model="form" size="mini" :label-width="formLabelWidth" label-position="left" style="margin:0 20px">
          <el-form-item label="物流">
            <el-select
              v-model="form.deliveryFeedBackInfo.idLogisticsInfo"
              filterable
              remote
              placeholder="请输入关键词"
              :remote-method="getDeliverDocInfo"
              :loading="deliverDocLoading">
              <el-option
                v-for="item in deliverDocOptions"
                :key="item.id"
                :label="item.logisticName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物流单号">
            <el-input
              placeholder="请输入内容"
              v-model="form.deliveryFeedBackInfo.logisticsCode"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="物流单日期">
            <el-date-picker
              v-model="form.deliveryFeedBackInfo.logisticsDate"
              type="date"
              value-format="yyyyMMdd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="收款方式">
            <el-radio-group v-model="form.deliveryFeedBackInfo.chargeKind">
              <el-radio :label="0">现金</el-radio>
              <el-radio :label="1">物流代收</el-radio>
              <el-radio :label="2">全额担保</el-radio>
              <el-radio :label="3">预存</el-radio>
              <el-radio :label="4">预收款</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-show="form.deliveryFeedBackInfo.chargeKind in [0,1]" label="代收金额">
            <el-input
              placeholder="请输入金额"
              type="number"
              min="0"
              v-model="form.deliveryFeedBackInfo.logisticsRecMoney">
            </el-input>
          </el-form-item>
          <el-form-item label="担保人">
            <el-select
              v-model="form.deliveryFeedBackInfo.idGuarantor"
              filterable
              remote
              placeholder="请输入关键词"
              :remote-method="getGuarantorInfo"
              :loading="guarantorLoading">
              <el-option
                v-for="item in guarantorOptions"
                :key="item.value"
                :label="item.guaranInfo"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="担保金额">
            <el-input
              placeholder="请输入金额"
              type="number"
              min="0"
              v-model="form.deliveryFeedBackInfo.guarantorMoney">
            </el-input>
          </el-form-item>
          <el-form-item label="收款说明">
            <el-input
              placeholder="请输入内容"
              v-model="form.deliveryFeedBackInfo.chargeMemo"
              type="textarea"
              :rows="5"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="cancelForm">取 消</el-button>
            <el-button type="primary" @click="submitForm" :loading="formLoading">
              {{ formLoading ? '提交中 ...' : '确 定' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

    <el-dialog title="发货单作废" :visible.sync="dialogBackVisible" width="30%">
      <el-form label-position="top" label-width="80px">
        <el-form-item label="发货退回原因">
          <el-input type="textarea" v-model="backForm.feedBackReturnMemo"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBackVisible = false">取 消</el-button>
        <el-button type="success" @click="voidSendBill(1)">退回重发</el-button>
        <el-button type="primary" @click="voidSendBill(2)">等待通知</el-button>
      </div>
    </el-dialog>

    <el-dialog title="订单详情" :close-on-click-modal="false" class="orderDetailDialog" :visible.sync="detailVisible"
               width="1200px">
      <order-detail ref="orderDetail"></order-detail>
    </el-dialog>
  </div>
</template>

<script>
import {
  getGuarantorInfoListFront,
  getLogisticsInfoList,
  getSendBillDetail,
  getSendBillList,
  printSendBill,
  updateDeliveryFeedBackInfo,
  voidSendBill
} from '@/api/delivery/delivery'
import OrderDetail from '@/components/orderDetail/orderDetail'
import {doLocalPrint, parseTime} from "@/utils";

const sendBillTbItems = [
  {
    name: '发货单号', field: 'billCode', width: '100'
  },
  {
    name: '制单时间', field: 'createTime', width: '100'
  },
  {
    name: '制单人', field: 'createMan', width: '70'
  },
  {
    name: '发货方式', field: 'orderSendKind', width: ''
  },
  {
    name: '运费', field: 'logisticsMoney', width: ''
  }
]

const defaultItems = [
  {
    name: '订单编号', field: 'orderCode', width: '100'
  },
  {
    name: '产品类型', field: 'productName', width: '100'
  },
  {
    name: '客户名称', field: 'clientName', width: '100'
  },
  {
    name: '订单名称', field: 'orderName', width: '120'
  },
  {
    name: '订单总额', field: 'orderMoneyTotal', width: '60'
  },
  {
    name: '应收金额', field: 'chargeMoney', width: '60'
  },
  {
    name: '定金', field: 'orderMoneyPre', width: '40'
  },
  {
    name: '已收金额', field: 'payMoney', width: '60'
  },
  {
    name: '订单收款方式', field: 'payKind', width: '160'
  },
  {
    name: '发货时间', field: 'sendDate', width: '120'
  },
  {
    name: '代收金额', field: 'collectMoney', width: '60'
  },
  {
    name: '担保人', field: 'guarantorName', width: '80'
  },
  {
    name: '担保金额', field: 'guarantorMoney', width: '60'
  },
  {
    name: '发货反馈人', field: 'feedBackMan', width: '100'
  },
  {
    name: '收款方式', field: 'feedBackPayKind', width: ''
  },
  {
    name: '发货人', field: 'deliverMan', width: '80'
  }
]

export default {
  components: {
    OrderDetail
  },
  data() {
    return {
      valueDate: null,
      rowIndex: '',
      showDrawer: false,
      search: {
        keyWord: '',
        beginTime: '',
        endTime: ''
      },
      billColumnNames: Object.assign([], sendBillTbItems),
      itemColumnNames: Object.assign([], defaultItems),

      listData: {
        total: 0,
        page: 1,
        pageSize: 20
      },

      detailVisible: false,
      dialogBackVisible: false,

      billListLoading: false,
      itemListLoading: false,
      billTableData: [],
      itemTableData: [],
      selectBillItems: [],
      backForm: {
        id: 0,
        feedBackReturnMemo: '',
        backKind: 0
      },

      formLoading: false,
      deliverDocLoading: false,
      guarantorLoading: false,
      deliverDocOptions: [],
      guarantorOptions: [],
      feedbackItem: null,
      form: {
        deliveryFeedBackInfo: {
          idSendBillItem: 0, // 关联发货明细id
          idOrder: 0, // 关联订单id,
          idLogisticsInfo: '', // 物流档案id
          logisticsCode: '', // 物流单号
          logisticsDate: parseTime(new Date(), '{y}{m}{d}'), // 物流单日期
          chargeKind: 0, // 收款方式
          logisticsRecMoney: 0, // 代收金额
          idGuarantor: '', // 担保人
          guarantorMoney: 0, // 担保金额
          chargeMemo: '' // 收款说明
        }
      },
      formLabelWidth: '100px'
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getpayKind(payKind) {
      const _that = this;
      // console.log(payKind);
      var htmls = "";
      var payKinds = [];
      var payKindArray = [];
      if(payKind){
        payKindArray = payKind.split('+')
        payKindArray.forEach(item => {
          var kindItem = item.split(':')
          payKinds.push(kindItem)
        })
        for (let i = 0; i < payKinds.length; i++) {
          var item = payKinds[i];
          if (item[1] == '担保人') {
            htmls += item[1] + "-" + item[2] + "-" + item[3]
          } else {
            htmls += item[1] + "-" + item[2]
          }
        }
      }

      // payKind = payKind.split('+')
      // payKind.forEach(item => {
      //   var kindItem = item.split(':')
      //   payKinds.push(kindItem)
      // })
      // console.log(payKinds);
      return htmls
    },
    getList() {
      const _that = this
      _that.billListLoading = true

      if (this.search.beginTime === '') {
        delete this.search.beginTime
      }

      if (this.search.endTime === '') {
        delete this.search.endTime
      }

      const params = _that.search
      const page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      const data = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page)
      }
      // console.log(data);
      getSendBillList(data).then(response => {
        // console.log(response)
        response.data.forEach(x => {
          x.orderSendKind = x.orderSendKind + '(' + x.linkMan + ')'
        })
        _that.billTableData = response.data
        _that.listData.total = response.total
        // console.log(_that.tableData)
        _that.billListLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.billListLoading = false
      })
    },

    getItemList(idSendBill) {
      const _that = this
      _that.itemListLoading = true

      const data = {
        'idSendBill': idSendBill
      }
      // console.log(data);
      getSendBillDetail(data).then(response => {
        // console.log(response)
        // //  组合表单数据
        const tableData = response.data.sendBillItemList
        // tableData.forEach(x => {
        //   x.referenceCode = x.orderCode + '/' + x.sendBillCode
        // })
        _that.itemTableData = tableData
        // console.log(_that.tableData)
        _that.itemListLoading = false
        for (let i = 0; i < _that.billTableData.length; i++) {
          var datas = _that.billTableData[i];
          if (idSendBill == datas.id) {
            _that.$set(datas, 'rowClick', false);
          } else {
            _that.$set(datas, 'rowClick', true);
          }
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.itemListLoading = false
      })
    },

    tableRefresh() {
      this.getList()
    },

    searchData() {
      if (this.valueDate) {
        this.search.beginTime = Date.parse(this.valueDate[0] + ' 00:00:00')
        this.search.endTime = Date.parse(this.valueDate[1] + ' 23:59:59')
      } else {
        this.search.beginTime = ''
        this.search.endTime = ''
      }
      this.listData.page = 1
      this.getList()
    },

    customRowStyle({row, rowIndex}) {
      if (row.voidFlag === 1) {
        return {
          color: '#F56C6C'
        }
      }
      // if (column.property === 'boxCount') {
      //   return 'background-color:#1989fa80;color:#fff;font-weight:600;'
      // }
      if (this.rowIndex === rowIndex) {
        return {
          'background-color': '#8cc5ff !important',
          'color': '#fff !important',
        }
      }
    },
    rowClassName({row, rowIndex}) {
      row.index = rowIndex
    },

    handleSendBillClickTableRow(row, column, event) {
      this.rowIndex = row.index;
      if (row.rowClick == false) {
        return
      }
      this.getItemList(row.id)
    },

    printSendBill() {
      if (this.selectBillItems.length === 0) {
        this.$message.error('请选择记录')
        return
      }

      const params = this.selectBillItems.map(x => x.id).join(',')
      // 打印出库单
      const printParam = {
        'ids': params
      }
      printSendBill(printParam).then(printResp => {
        const printData = {
          '_rootData': printResp.data.resultMap.PrintData
        }
        // console.log(PrintData);
        const pData = {
          PrintTemplate: 'SendBill.fr3',
          NeedPreview: 1,
          PrintData: JSON.stringify(printData)
        }

        doLocalPrint(pData)
      })
    },

    onTableSelectionChange(val) {
      this.selectBillItems = val
    },

    showDialogVoidSendBill(row) {
      this.backForm.id = row.id
      this.backForm.feedBackReturnMemo = ''
      this.dialogBackVisible = true
    },

    voidSendBill(backKind) {
      this.$confirm('确定要作废发货单吗？')
        .then(_ => {
          this.backForm.backKind = backKind
          const data = this.backForm
          // console.log(data);
          const _that = this
          voidSendBill(data).then(response => {
            console.log(response)
            _that.dialogBackVisible = false
            _that.$message.success('发货单已作废')
            _that.tableRefresh()
          }).catch(err => {
            _that.$message.error(err)
          })
        })
        .catch(_ => {
        })
    },

    // 获取订单信息
    openDetail(row) {
      var _that = this
      _that.detailVisible = true
      _that.$nextTick(() => {
        _that.$refs.orderDetail.idOrder = row.idOrder
        _that.$refs.orderDetail.getInfo()
      })
    },
    columnFormatter(row, column) {
      if (column.property === 'createTime' || column.property === 'deliverDate') {
        return row[column.property] ? row[column.property].substring(0, 10) : row[column.property]
      } else return row[column.property]
    },

    showFeedbackDrawer(row) {
      this.feedbackItem = row

      // 解析一下收款方式
      var payKinds = []
      var payKind = []
      payKind = row.payKind.split('+')
      payKind.forEach(item => {
        item = item.split(':')
        payKinds.push(item)
      })
      payKinds.forEach(x => {
        if (x[0] === '2') {
          // 担保人
          this.form.deliveryFeedBackInfo.guarantorMoney = x[2]
        }
      })

      this.showDrawer = true
    },
    // 获取担保人档案
    getGuarantorInfo(query) {
      if (query !== '') {
        this.guarantorLoading = true

        const params = {
          params: {
            keyWord: query
          }
        }
        const _that = this
        getGuarantorInfoListFront(params).then(response => {
          console.log(response)
          _that.guarantorLoading = false
          _that.guarantorOptions = response.data
          _that.guarantorOptions.forEach(x => {
            x.guaranInfo = x.personName + '(' + x.overMoney + ')'
          })
        }).catch(err => {
          _that.$message.error(err)
        })
      } else {
        this.guarantorOptions = []
      }
    },
    // 获取物流档案
    getDeliverDocInfo(query) {
      if (query !== '') {
        this.deliverDocLoading = true

        const params = {
          params: {
            keyWord: query
          }
        }
        const _that = this
        getLogisticsInfoList(params).then(response => {
          console.log(response)
          _that.deliverDocLoading = false
          _that.deliverDocOptions = response.data
        }).catch(err => {
          _that.$message.error(err)
        })
      } else {
        this.deliverDocOptions = []
      }
    },

    submitForm() {
      if (this.formLoading) {
        return
      }
      // this.form.deliveryFeedBackInfo.guarantorMoney = trimAll(this.form.deliveryFeedBackInfo.guarantorMoney)
      // this.form.deliveryFeedBackInfo.logisticsRecMoney = trimAll(this.form.deliveryFeedBackInfo.logisticsRecMoney)
      // 数据校验
      if (this.form.deliveryFeedBackInfo.chargeKind === 2 &&
        this.form.deliveryFeedBackInfo.idGuarantor <= 0) {
        this.$message.error('请选择担保人')
        return
      }

      if (this.form.deliveryFeedBackInfo.guarantorMoney > 0 &&
        this.form.deliveryFeedBackInfo.idGuarantor <= 0) {
        this.$message.error('请选择担保人')
        return
      }

      this.$confirm('确定要提交反馈吗？')
        .then(_ => {
          this.formLoading = true
          this.toFeedbackItem()

        })
        .catch(_ => {
        })
    },

    toFeedbackItem() {
      this.form.deliveryFeedBackInfo.idSendBillItem = this.feedbackItem.id
      this.form.deliveryFeedBackInfo.idOrder = this.feedbackItem.idOrder

      const params = {
        'deliveryFeedBackInfo': JSON.stringify(this.form.deliveryFeedBackInfo)
      }

      console.log(params);
      const _that = this
      updateDeliveryFeedBackInfo(params).then(response => {
        console.log(response)
        if (response.httpCode === 200) {
          _that.$message.success('发货反馈完成')
          // 动画关闭需要一定的时间
          setTimeout(() => {
            _that.tableRefresh()
            _that.$refs.deliverFeedbackDrawer.closeDrawer()
          }, 400)
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
      _that.formLoading = false
    },
    cancelForm() {
      this.formLoading = false
      this.$refs.deliverFeedbackDrawer.closeDrawer()
    },
    drawerClose(done) {
      this.feedbackItem = null
      // 关掉之后清除数据
      this.form = {
        deliveryFeedBackInfo: {
          idSendBillItem: 0, // 关联发货明细id
          idOrder: 0, // 关联订单id,
          idLogisticsInfo: '', // 物流档案id
          logisticsCode: '', // 物流单号
          logisticsDate: parseTime(new Date(), '{y}{m}{d}'), // 物流单日期
          chargeKind: 0, // 收款方式
          logisticsRecMoney: 0, // 代收金额
          idGuarantor: '', // 担保人
          guarantorMoney: 0, // 担保金额
          chargeMemo: '' // 收款说明
        }
      }
      done()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.el-drawer {
  overflow: scroll
}

:focus {
  outline: 0;
}
</style>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 480px;
}
</style>


<style lang="scss" scoped>
.filter-container {
  margin-bottom: 15px;
}

.board-column {
  min-width: 100px;
  min-height: 100px;
  height: auto;
  overflow: hidden;
  background: #f0f0f0;
  border-radius: 3px;

  .board-column-header {
    height: 50px;
    line-height: 50px;
    overflow: hidden;
    padding: 0 20px;
    text-align: center;
    background: #333;
    color: #fff;
    border-radius: 3px 3px 0 0;
  }

  .board-column-content {
    height: auto;
    overflow: hidden;
    border: 10px solid transparent;
    min-height: 60px;
    display: flex;
    justify-content: flex-start;
    flex-direction: column;
    align-items: center;

    .board-item {
      cursor: pointer;
      width: 100%;
      height: 64px;
      margin: 5px 0;
      background-color: #fff;
      text-align: left;
      line-height: 54px;
      padding: 5px 10px;
      box-sizing: border-box;
      box-shadow: 0px 1px 3px 0 rgba(0, 0, 0, 0.2);
    }
  }
}
</style>
