<template>
  <a-modal
    centered
    class="sendGood-detail-modal"
    :footer="null"
    :maskClosable="false"
    v-model="isShow"
    :title="modalTit"
    @cancel="handleCommonCancel"
    width="60%">
    <a-spin :spinning="spinning" tip="Loading...">
      <div class="common-main">
        <div style="display:flex;margin-bottom:10px;align-items: center;">
          <a-button @click="showGlModal=true" type="primary" style="margin-right:10px" ghost v-if="isEdit">选择关联单据</a-button>
          <div v-if="sendBillStockOutList.length">
            <a-alert type="info">
              <div slot="message">{{ customeName }}，共 {{ sendBillStockOutList && sendBillStockOutList.length }} 个出库单，产品款数合计 <span>{{ productTotal&&productTotal.totalCategory }}</span> ，产品数量合计 <span>{{ productTotal&&productTotal.totalQty }}</span>。</div>
            </a-alert>
          </div>
        </div>
        <div style="margin-bottom:10px;" v-if="isEdit">
          <a-table :columns="glColumns" :pagination="false" :scroll="{ y: 200 }" :data-source="sendBillStockOutList" bordered>
            <!-- 客户名称 -->
            <template slot="buyerName" slot-scope="text, record">
              {{ record.buyerName || record.demanderName }}
            </template>
            <!-- 操作 -->
            <template slot="action" slot-scope="text, record">
              <a-button
                size="small"
                type="link"
                class="button-error"
                @click="delStockOutList(record)"
              >
                删除
              </a-button>
            </template>
          </a-table>
        </div>
        <div class="toolsBar">
          <a-form-model
            ref="ruleForm"
            :model="form"
            :rules="rules"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
          >
            <a-row>
              <a-col span="8">
                <a-form-model-item label="托运日期" prop="sendDate">
                  <a-date-picker :allowClear="false" inputReadOnly v-model="form.sendDate" :locale="locale"/>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="收货人" prop="customerCacateName">
                  <a-input placeholder="请输入收货人(最多30字符)" :maxLength="30" v-model.trim="form.customerCacateName"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="电话" prop="customerCacatePhone">
                  <a-input placeholder="请输入电话" :maxLength="30" v-model.trim="form.customerCacatePhone"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col span="24">
                <a-form-model-item label="详细地址" prop="customerAddressDetail" :label-col="{span:2}" :wrapper-col="{span:21}">
                  <a-textarea placeholder="请输入详细地址(最多300字符)" :maxLength="300" v-model.trim="form.customerAddressDetail"></a-textarea>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="目的地">
                  <a-input placeholder="请输入目的地(最多30字符)" :maxLength="30" v-model.trim="form.customerAddress"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="物流电话" prop="transportTele">
                  <a-input placeholder="请输入物流电话" :maxLength="30" v-model.trim="form.transportTele"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="物流单号" prop="transportNo">
                  <a-input placeholder="请输入物流单号" :maxLength="30" v-model.trim="form.transportNo"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="付款方式">
                  <v-select
                    v-model="form.payType"
                    ref="payType"
                    code="SEND_BILL_PAY_TYPE"
                    placeholder="请选择付款方式"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="交货方式">
                  <v-select
                    v-model="form.handoverType"
                    ref="handoverType"
                    code="SEND_BILL_HANDOVER_TYPE"
                    placeholder="请选择交货方式"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="运费合计">
                  <!-- <a-input disabled placeholder="请输入运费合计" v-model.trim="form.totalSendAmount"></a-input> -->
                  {{ form.totalSendAmount ? toThousands(form.totalSendAmount) : '--' }}
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
        <div>
          <a-table
            class="sTable"
            :columns="columns"
            :pagination="false"
            :scroll="{ y: 200 }"
            :data-source="tableData"
            bordered>
            <!-- 物品名称 -->
            <template slot="goodName" slot-scope="text, record">
              <a-select v-model="record.goodsName" placeholder="请选择物品" style="width: 100%">
                <a-select-option value="电池机油">
                  电池机油
                </a-select-option>
                <a-select-option value="易损件">
                  易损件
                </a-select-option>
                <a-select-option value="电池">
                  电池
                </a-select-option>
                <a-select-option value="机油">
                  机油
                </a-select-option>
                <a-select-option value="轮胎">
                  轮胎
                </a-select-option>
              </a-select>
            </template>
            <!-- 数量 -->
            <template slot="qty" slot-scope="text, record">
              <a-input-number style="width: 100%;" :precision="0" v-model="record.goodsQty" :min="1" :max="99999999"></a-input-number>
            </template>
            <!-- 体积 -->
            <template slot="volume" slot-scope="text, record">
              <a-input-number style="width: 100%;" :precision="2" v-model="record.goodsVolume" :min="0" :max="99999999"></a-input-number>
            </template>
            <!-- 重量 -->
            <template slot="weight" slot-scope="text, record">
              <a-input-number style="width: 100%;" :precision="2" v-model="record.goodsWeight" :min="0" :max="99999999"></a-input-number>
            </template>
            <!-- 计费单价 -->
            <template slot="price" slot-scope="text, record">
              <a-input-number style="width: 100%;" :precision="2" v-model="record.unitPrice" :min="0" :max="99999999"></a-input-number>
            </template>
            <!-- 运费 -->
            <template slot="freight" slot-scope="text, record">
              <a-input-number
                style="width: 100%;"
                :precision="2"
                @change="amountChange('transportAmount',record)"
                v-model="record.transportAmount"
                :min="0"
                :max="99999999"></a-input-number>
            </template>
            <!-- 保价 -->
            <template slot="supportValue" slot-scope="text, record">
              <a-input-number style="width: 100%;" :precision="2" v-model="record.supportValue" :min="0" :max="99999999"></a-input-number>
            </template>
            <!-- 送货费 -->
            <template slot="deliveryExpense" slot-scope="text, record">
              <a-input-number
                style="width: 100%;"
                :precision="2"
                @change="amountChange('sendAmount',record)"
                v-model="record.sendAmount"
                :min="0"
                :max="99999999"></a-input-number>
            </template>
            <!-- 其他 -->
            <template slot="other" slot-scope="text, record">
              <a-input-number
                style="width: 100%;"
                :precision="2"
                @change="amountChange('otherAmount',record)"
                v-model="record.otherAmount"
                :min="0"
                :max="99999999"></a-input-number>
            </template>
            <!-- 操作 -->
            <template slot="action" slot-scope="text, record, index">
              <a-button
                size="small"
                type="link"
                class="button-error"
                @click="handleDel(record,index)"
              >
                删除
              </a-button>
            </template>
          </a-table>
          <div style="padding: 5px; border:1px solid #eee;border-radius:0 0 10px;border-top: 0;text-align:center;">
            <a-button @click="addItem()" type="link">+新增发货明细</a-button>
          </div>
        </div>
      </div>
      <div class="btn-box">
        <a-button @click="handleCommonCancel" v-if="isCancel">{{ cancelText }}</a-button>
        <a-button type="primary" @click="handleCommonOk">{{ okText }}</a-button>
      </div>
    </a-spin>
    <!-- 关联单据 -->
    <selectGlOrderModal
      ref="selGlModal"
      modalTit="选择关联单据"
      :chooseData="sendBillStockOutList"
      :openModal="showGlModal"
      @choose="getProductTotal"
      @cancel="showGlModal=false"></selectGlOrderModal>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
import { STable, VSelect } from '@/components'
import selectGlOrderModal from './selectGlOrderModal.vue'
import { sendBillInsert, sendBillFindBySn, sendBillUpdate, deleteSendBillStockOut } from '@/api/sendBill'
export default {
  name: 'SendGoodModal',
  mixins: [commonMixin],
  components: { STable, VSelect, selectGlOrderModal },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    modalTit: { // 弹框标题
      type: String,
      default: null
    },
    okText: { // 确定 按钮文字
      type: String,
      default: '确定'
    },
    cancelText: { // 取消 按钮文字
      type: String,
      default: '取消'
    },
    isCancel: { // 是否显示  取消 按钮
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      locale,
      isShow: this.openModal, //  是否打开弹框
      disabled: false,
      spinning: false,
      showGlModal: false,
      form: {
        'stockOutSnList': [], // 出库单列表
        'sendDate': moment(), // 托运时间
        'customerAddress': '', // 目的地
        'customerAddressDetail': '', // 详细地址
        'transportTele': '', // 物流电话
        'transportNo': '', // 物流单号
        'customerCacateName': '', // 收货人
        'customerCacatePhone': '', // 收货人电话
        'payType': '', // 收款方式
        'handoverType': '', // 发货方式
        'totalSendAmount': '', // 发货总费用
        'sendBillDetailList': [] // 发货列表
      },
      rules: {
        sendDate: [{ required: true, message: '请选择托运日期', trigger: 'change' }],
        customerCacateName: [{ required: true, message: '请输入收货人', trigger: 'change' }],
        customerCacatePhone: [{ required: true, message: '请输入电话', trigger: 'change' }],
        customerAddressDetail: [{ required: true, message: '请输入详细地址', trigger: 'change' }]
      },
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 15 }
      },
      sendBillStockOutList: [],
      glColumns: [
        { title: '序号', dataIndex: 'no', width: '6%', align: 'center', customRender: function (text) { return text } },
        { title: '出库单号', dataIndex: 'stockOutNo', width: '10%', align: 'center' },
        { title: '业务单号', dataIndex: 'outBizSubNo', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '出库类型', dataIndex: 'outBizTypeDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '发货编号', dataIndex: 'sendNo', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', scopedSlots: { customRender: 'buyerName' }, width: '12%', align: 'center', ellipsis: true },
        { title: '收货客户名称', dataIndex: 'receiverName', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品款数', dataIndex: 'productTotalCategory', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '产品数量', dataIndex: 'productTotalQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单据审核时间', dataIndex: 'auditTime', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '收款时间', dataIndex: 'settleTime', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '6%', align: 'center' }
      ],
      productTotal: null,
      tableData: [],
      columns: [
        { title: '序号', dataIndex: 'no', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '货物名称', dataIndex: 'goodsName', scopedSlots: { customRender: 'goodName' }, width: '10%', align: 'center' },
        { title: '件数', dataIndex: 'goodsQty', scopedSlots: { customRender: 'qty' }, width: '8%', align: 'center' },
        { title: '体积（m³）', dataIndex: 'goodsVolume', scopedSlots: { customRender: 'volume' }, width: '8%', align: 'center' },
        { title: '重量（kg）', dataIndex: 'goodsWeight', scopedSlots: { customRender: 'weight' }, width: '8%', align: 'center' },
        { title: '计费单价（元）', dataIndex: 'unitPrice', scopedSlots: { customRender: 'price' }, width: '9%', align: 'center' },
        { title: '运费（元）', dataIndex: 'transportAmount', scopedSlots: { customRender: 'freight' }, width: '9%', align: 'center' },
        { title: '保价（万）', dataIndex: 'supportValue', scopedSlots: { customRender: 'supportValue' }, width: '9%', align: 'center' },
        { title: '送货费', dataIndex: 'sendAmount', scopedSlots: { customRender: 'deliveryExpense' }, width: '9%', align: 'center' },
        { title: '其他', dataIndex: 'otherAmount', scopedSlots: { customRender: 'other' }, width: '8%', align: 'center' },
        { title: '合计', dataIndex: 'totalAmount', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ],
      isEdit: false,
      customeName: ''
    }
  },
  methods: {
    // 新增,出库单和收货人信息
    setData (data, customeInfo) {
      this.sendBillStockOutList = data
      this.customeName = data[0].demanderName
      this.isEdit = false
      this.addItem()
      this.getProductTotal()
      if (customeInfo) {
        this.form.customerCacateName = customeInfo.consigneeName
        this.form.customerCacatePhone = customeInfo.consigneeTel
        this.form.customerAddressDetail = customeInfo.addr
      }
    },
    // 删除出库单
    delStockOutList (row) {
      if (this.sendBillStockOutList && this.sendBillStockOutList.length == 1) {
        this.$message.warning('发货单必须关联相关出库单号！')
        return
      }
      const ri = this.sendBillStockOutList.findIndex(item => row.stockOutSn == item.stockOutSn)
      // 新加的
      if (ri > -1) {
        this.sendBillStockOutList.splice(ri, 1)
        this.getProductTotal()
      }
      // if (row.id) {
      // this.sendBillStockOutList.splice(ri, 1)
      // this.getProductTotal()
      // } else {
      //   // 删除后修改发货状态
      //   this.spinning = true
      //   deleteSendBillStockOut({ stockOutSn: row.stockOutSn, sendBillSn: this.form.sendBillSn }).then(res => {
      //     if (res.status == 200) {
      //       this.sendBillStockOutList.splice(ri, 1)
      //       this.getProductTotal()
      //     }
      //     this.spinning = false
      //   })
      // }
    },
    // 编辑
    getDetail (data) {
      this.spinning = true
      this.isEdit = true
      this.customeName = data.customeName
      sendBillFindBySn({ sn: data.sendBillSn }).then(res => {
        console.log(res)
        this.spinning = false
        if (res.data) {
          this.sendBillStockOutList = res.data.sendBillStockOutList // 出库单
          this.tableData = res.data.detailList // 发货明细
          this.tableData.map((item, i) => {
            item.no = i + 1
          })
          // 统计出库单
          this.getProductTotal()
          // 基本信息
          this.form.customerCacateName = res.data.customerCacateName
          this.form.customerCacatePhone = res.data.customerCacatePhone
          this.form.customerAddress = res.data.customerAddress
          this.form.customerAddressDetail = res.data.customerAddressDetail
          this.form.transportTele = res.data.transportTele
          this.form.transportNo = res.data.transportNo
          this.form.sendDate = res.data.sendDate
          this.form.payType = res.data.payType
          this.form.handoverType = res.data.handoverType
          this.form.totalSendAmount = res.data.totalSendAmount
          this.form.sendBillNo = data.sendBillNo
          this.form.sendBillSn = data.sendBillSn
        }
      })
    },
    // 出库单数据统计
    getProductTotal () {
      const ret = {
        totalCategory: 0,
        totalQty: 0
      }
      const stockOutSnList = []
      this.sendBillStockOutList.map((item, index) => {
        item.no = index + 1
        ret.totalCategory = ret.totalCategory + item.productTotalCategory
        ret.totalQty = ret.totalQty + item.productTotalQty
        stockOutSnList.push(item.stockOutSn)
      })
      // 编辑时不需要传
      this.form.stockOutSnList = stockOutSnList
      this.productTotal = ret
    },
    // 计算运费合计
    getTotalSendAmount () {
      let ret = 0
      this.tableData.map((item, i) => {
        item.no = i + 1
        ret = ret + Number(item.totalAmount || 0)
      })
      this.form.totalSendAmount = ret.toFixed(2)
    },
    // 计算每行发货费用合计
    amountChange (key, record) {
      record.totalAmount = (record.transportAmount || 0) + (record.sendAmount || 0) + (record.otherAmount || 0)
      record.totalAmount = Number(record.totalAmount).toFixed(2)
      this.getTotalSendAmount()
    },
    // 删除
    handleDel (row, index) {
      this.tableData.splice(index, 1)
      this.getTotalSendAmount()
    },
    // 添加
    addItem () {
      const len = this.tableData.length
      this.tableData.push({
        'no': len + 1,
        'goodsName': undefined,
        'goodsQty': '',
        'goodsVolume': '',
        'goodsWeight': '',
        'unitPrice': '',
        'transportAmount': '',
        'supportValue': '',
        'sendAmount': '',
        'otherAmount': '',
        'totalAmount': ''
      })
    },
    // 校验物品单
    vaildGood (key) {
      const ret = []
      this.tableData.map(item => {
        ret.push(!!item[key])
      })
      console.log(ret)
      return ret
    },
    // 确定
    handleCommonOk () {
      const _this = this
      if (_this.form.stockOutSnList.length == 0 && !this.isEdit) {
        _this.$message.info('请选择出库单！')
        return
      }
      this.$refs.ruleForm.validate(valid => {
        _this.form.sendBillDetailList = _this.tableData
        if (valid) {
          console.log(_this.form, this.isEdit)
          if (_this.form.sendBillDetailList.length == 0) {
            _this.$message.info('请新增发货明细！')
            return false
          }
          if (_this.vaildGood('goodsName').indexOf(false) >= 0) {
            _this.$message.info('请选择物品！')
            return false
          }
          if (_this.vaildGood('goodsQty').indexOf(false) >= 0) {
            _this.$message.info('请输入件数！')
            return false
          }
          if (_this.vaildGood('totalAmount').indexOf(false) >= 0) {
            _this.$message.info('请输入费用！')
            return false
          }

          const baseUrl = this.isEdit ? sendBillUpdate : sendBillInsert
          _this.spinning = true
          baseUrl(_this.form).then(res => {
            if (res.status == 200) {
              _this.$emit('ok')
              _this.isShow = false
              _this.$message.success(res.message)
            }
            _this.spinning = false
          })
        } else {
          return false
        }
      })
    },
    // 取消
    handleCommonCancel () {
      this.$emit('cancel')
      this.tableData = []
      this.sendBillStockOutList = []
      this.spinning = false
      this.$refs.ruleForm.resetFields()
      this.form = {
        'stockOutSnList': [], // 出库单列表
        'sendDate': moment(), // 托运时间
        'customerAddress': '', // 目的地
        'customerAddressDetail': '', // 详细地址
        'transportTele': '', // 物流电话
        'transportNo': '', // 物流单号
        'customerCacateName': '', // 收货人
        'customerCacatePhone': '', // 收货人电话
        'payType': '', // 收款方式
        'handoverType': '', // 发货方式
        'totalSendAmount': '', // 发货总费用
        'sendBillDetailList': [] // 发货列表
      }
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.handleCommonCancel()
      }
    }
  }
}
</script>

<style lang="less">
  .sendGood-detail-modal{
    .common-main{
       .toolsBar{
         padding-top:15px;
         border:1px solid #eee;
         border-radius: 3px;
         display: flex;
         align-items: center;
         margin-bottom: 10px;
         .ant-form-item{
           margin-bottom: 5px;
         }
         .ant-btn{
           margin-left: 30px;
         }
       }
    }
    .btn-box{
      text-align: center;
      margin-top: 30px;
      .ant-btn{
        margin:0 10px;
      }
    }
  }
</style>
