<template>
  <a-modal
    centered
    class="sendGood-detail-modal"
    :footer="null"
    :maskClosable="false"
    v-model="isShow"
    :title="modalTit"
    @cancle="isShow=false"
    width="60%">
    <a-spin :spinning="spinning" tip="Loading...">
      <div class="common-main">
        <a-alert type="info" v-if="detail.length" style="margin-bottom:10px">
          <div slot="message">箭冠汽配西安大兴店，共 {{ detail && detail.length }} 个出库单，产品款数合计 <span>{{ productTotal&&productTotal.totalCategory }}</span> ，产品数量合计 <span>{{ productTotal&&productTotal.totalQty }}</span>。</div>
        </a-alert>
        <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="12">
                <a-form-model-item label="托运日期" prop="sendDate">
                  <a-date-picker v-model="form.sendDate" :locale="locale"/>
                </a-form-model-item>
              </a-col>
              <a-col span="12">
                <a-form-model-item label="目的地">
                  <a-input placeholder="请输入目的地" v-model.trim="form.customerAddress"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col span="12">
                <a-form-model-item label="收货人" prop="customerCacateName">
                  <a-input placeholder="请输入收货人" v-model.trim="form.customerCacateName"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col span="12">
                <a-form-model-item label="电话" prop="customerCacatePhone">
                  <a-input placeholder="请输入电话" 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:3}" :wrapper-col="{span:19}">
                  <a-textarea placeholder="请输入详细地址" v-model.trim="form.customerAddressDetail"></a-textarea>
                </a-form-model-item>
              </a-col>
              <a-col span="12">
                <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="12">
                <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="12">
                <a-form-model-item label="运费合计">
                  <a-input disabled placeholder="请输入运费合计" v-model.trim="form.totalSendAmount"></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
        <div>
          <a-table :columns="columns" :pagination="false" :scroll="{ y: 200 }" :data-source="tableData" bordered>
            <!-- 物品名称 -->
            <template slot="goodName" slot-scope="text, record">
              <a-select v-model="record.goodsName" 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>
            </template>
            <!-- 数量 -->
            <template slot="qty" slot-scope="text, record">
              <a-input-number style="width: 100%;" :precision="0" v-model="record.goodsQty" :min="0" :max="999999"></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="999999"></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="999999"></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="999999"></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="999999"></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="999999"></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="999999"></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="999999"></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;">
            <a-button @click="addItem()" type="link" block>+新增发货明细</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>
  </a-modal>
</template>

<script>
import moment from 'moment'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
import { STable, VSelect } from '@/components'
import { sendBillInsert } from '@/api/sendBill'
export default {
  name: 'CommonModal',
  components: { STable, VSelect },
  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,
      form: {
        'stockOutSnList': [], // 出库单列表
        'sendDate': moment(), // 托运时间
        'customerAddress': '', // 目的地
        'customerAddressDetail': '', // 详细地址
        '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 }
      },
      detail: [],
      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' }
      ]
    }
  },
  methods: {
    setData (data) {
      this.detail = data
      this.getProductTotal()
    },
    // 出库单数据统计
    getProductTotal () {
      const ret = {
        totalCategory: 0,
        totalQty: 0
      }
      const stockOutSnList = []
      this.detail.map(item => {
        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 => {
        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.tableData.map((item, i) => {
        item.no = i + 1
      })
      this.getTotalSendAmount()
    },
    // 添加
    addItem () {
      const len = this.tableData.length
      this.tableData.push({
        'no': len + 1,
        'goodsName': '',
        'goodsQty': '',
        'goodsVolume': '',
        'goodsWeight': '',
        'unitPrice': '',
        'transportAmount': '',
        'supportValue': '',
        'sendAmount': '',
        'otherAmount': '',
        'totalAmount': ''
      })
    },
    // 确定
    handleCommonOk () {
      const _this = this
      if (_this.form.stockOutSnList.length == 0) {
        _this.$message.info('请选择出库单！')
        return
      }
      this.$refs.ruleForm.validate(valid => {
        _this.form.sendBillDetailList = _this.tableData
        if (valid) {
          if (_this.form.sendBillDetailList.length == 0) {
            _this.$message.info('请新增发货明细！')
            return false
          }
          console.log(_this.form)
          sendBillInsert(_this.form).then(res => {
            if (res.status == 200) {
              _this.$emit('ok')
              _this.isShow = false
              _this.$message.success(res.message)
            }
          })
        } else {
          return false
        }
      })
    },
    // 取消
    handleCommonCancel () {
      this.$emit('cancel')
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('cancel')
      }
    }
  }
}
</script>

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