<template>
  <div class="billOfLadingEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="billOfLadingEdit-cont" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="billOfLadingEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
        </template>
      </a-page-header>
      <a-form-model
        id="billOfLadingEdit-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol">
        <a-card :bordered="false" class="billOfLadingEdit-cont">
          <a-row>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="申请人" prop="applyPersonSn">
                <employee style="width: 100%;" id="billOfLading-Employee" @change="employeeChange" v-model="form.applyPersonSn"></employee>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="主题" prop="theme">
                <a-input
                  id="billOfLadingEdit-theme"
                  :maxLength="30"
                  v-model.trim="form.theme"
                  placeholder="请输入主题(最多30个字符)"
                  allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="物流公司">
                <logisticsCompany
                  id="billOfLadingEdit-logisticsCompany"
                  ref="logisticsCompany"
                  @change="changeCompany"
                  v-model.trim="form.logisticsCompany"
                />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="物流点">
                <logisticsPoint
                  ref="logisticsPoint"
                  id="billOfLadingEdit-logisticsPoint"
                  v-model.trim="form.logisticsPoint"
                  allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="发货方">
                <dealerSubareaScopeList placeholder="请输入经销商名称搜索" ref="dealerSubareaScopeList" id="billOfLadingEdit-senderName" @change="custChange" />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="收货人">
                <SelectInput
                  v-model="form.receiverName"
                  id="billOfLadingEdit-receiverName"
                  code="CONSIGNEE"
                  placeholder="请选择或输入收货人(最多30字符)"
                  @loaded="v=>form.receiverName?'':form.receiverName=v[0]"
                  allowClear
                ></SelectInput>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="电话">
                <a-input
                  id="billOfLadingEdit-receiverPhone"
                  :maxLength="30"
                  v-model.trim="form.receiverPhone"
                  placeholder="请输入电话(最多30个字符)"
                  allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="件数">
                <a-input-number
                  id="billOfLadingEdit-goodsNum"
                  style="width:100%"
                  v-model="form.goodsNum"
                  :precision="0"
                  :min="1"
                  :max="99999999"
                  placeholder="请输入件数"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="运费" :label-col="{span:2}" :wrapper-col="{span:20}">
                <a-input
                  id="billOfLadingEdit-freight"
                  :maxLength="100"
                  v-model.trim="form.freight"
                  placeholder="请输入运费(最多100个字符)"
                  allowClear />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :spna="24">
              <a-form-model-item style="margin-bottom:0" label="备注" :label-col="{span:2}" :wrapper-col="{span:20}">
                <a-textarea
                  v-model.trim="form.remarks"
                  id="billOfLadingEdit-remarks"
                  :maxLength="500"
                  allowClear
                  placeholder="请输入备注(最多500个字符)" />
              </a-form-model-item>
            </a-col>
            <a-col :spna="24">
              <a-form-model-item label="退货仓库" :label-col="{span:2}" :wrapper-col="{span:20}" prop="warehouseSn">
                <chooseWarehouse ref="warehouse" @load="loadWarehouseVal" :isDefault="!$route.params.sn" v-model="form.warehouseSn" @change="handleWarehouse"></chooseWarehouse>
              </a-form-model-item>
            </a-col>
            <a-col :spna="24">
              <a-form-model-item label="附件" help="说明：支持图片、word、excel、PDF等格式，最多10个附件。" :label-col="{span:2}" :wrapper-col="{span:20}">
                <Upload
                  style="height: 100%;"
                  id="billOfLadingEdit-attachList"
                  v-model="form.attachmentList"
                  ref="attachList"
                  :fileSize="10"
                  :maxNums="10"
                  fileType="*"
                  uploadType="attach"
                  :action="attachAction"
                  @change="changeAttach"
                  upText="上传附件"></Upload>
              </a-form-model-item>
            </a-col>
            <a-col :spna="24" v-show="form.warehouseSn">
              <a-form-model-item label="关联销退单" :label-col="{span:2}" :wrapper-col="{span:20}">
                <a-button type="primary" class="button-primary" @click="openSelModal">选择销退单</a-button>
                <div style="margin-top:10px;">
                  <v-table
                    ref="salesReturnOrderTable"
                    :columns="columns"
                    :scroll="{ y: 300 }"
                    :showPagination="false"
                    :data-source="chooseData"
                    bordered>
                    <!-- 编号 -->
                    <template slot="no" slot-scope="text, record,index">
                      <span>{{ index+1 }}</span>
                    </template>
                    <!-- 单号 -->
                    <template slot="salesReturnNo" slot-scope="text, record">
                      <span>{{ record.salesReturnBillNo }}</span>
                    </template>
                    <!-- 操作 -->
                    <template slot="action" slot-scope="text, record">
                      <a-button
                        size="small"
                        type="link"
                        class="button-error"
                        @click="handleDel(record)"
                      >
                        删除
                      </a-button>
                    </template>
                  </v-table>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form-model>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        size="large"
        class="button-success"
        :disabled="spinning"
        id="billOfLadingEdit-save-btn"
        @click="handleSave('save')"
        style="padding: 5px 50px;">保存</a-button>
      <a-button
        type="primary"
        class="button-primary"
        size="large"
        :disabled="spinning"
        id="billOfLadingEdit-submit-btn"
        @click="handleSave('submit')"
        style="padding: 5px 50px;">提交</a-button>
    </div>
    <!-- 关联销退单 -->
    <selectXtModal
      ref="selXtModal"
      modalTit="选择销退单"
      :chooseData="chooseData"
      :openModal="showXtModal"
      :warehouseSn="form.warehouseSn"
      @cancel="closeModal"></selectXtModal>
    <!-- 选择审核人员 -->
    <chooseDepartUserModal type="billOfLading" :showDefUser="true" :openModal="openDepartUserModal" @close="closeModal" @submit="handleSubmit"></chooseDepartUserModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VTable, VSelect, SelectInput, Upload } from '@/components'
import { pickUpSave, pickUpSubmit, pickUpDetail, pickUpDetailQueryList } from '@/api/pickUp'
import selectXtModal from './selectXtModal.vue'
import employee from '../../expenseManagement/expenseReimbursement/employee.js'
import logisticsCompany from './logisticsCompany.js'
import logisticsPoint from './logisticsPoint'
import chooseDepartUserModal from '../../expenseManagement/expenseReimbursement/chooseDepartUserModal.vue'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
export default {
  name: 'ProductInfoEdit',
  mixins: [commonMixin],
  components: { VSelect, SelectInput, Upload, VTable, employee, dealerSubareaScopeList, chooseDepartUserModal, selectXtModal, logisticsCompany, logisticsPoint, chooseWarehouse },
  data () {
    return {
      spinning: false,
      showXtModal: false,
      openDepartUserModal: false,
      pickUpSn: '',
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 }
      },
      attachAction: process.env.VUE_APP_API_BASE_URL + '/uploadGetFileInfo',
      form: {
        applyPersonSn: undefined, // 申请人
        applyPersonName: undefined,
        theme: '关于提货事宜', //  主题
        logisticsCompany: undefined, //  物流公司
        logisticsPoint: undefined, //  物流点
        senderName: '', //  发货方
        senderSn: '',
        receiverName: '', //  收货人
        receiverPhone: '', // 电话
        goodsNum: '', // 件数
        freight: '', // 运费
        remarks: '',
        attachmentList: '', // 附件
        warehouseSn: undefined// 退货仓库
      },
      salerReturnWsn: undefined,
      attachList: [],
      rules: {
        applyPersonSn: [
          { required: true, message: '请选择申请人', trigger: 'blur' }
        ],
        theme: [
          { required: true, message: '请输入主题', trigger: 'blur' }
        ],
        warehouseSn: [
          { required: true, message: '请选择退货仓库', trigger: 'change' }
        ]
      },
      chooseData: [],
      columns: [
        { title: '序号', scopedSlots: { customRender: 'no' }, width: '4%', align: 'center' },
        { title: '总部销退单号', scopedSlots: { customRender: 'salesReturnNo' }, width: '15%', align: 'center' },
        { title: '客户名称', dataIndex: 'buyerName', width: '20%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '申请退货数量', dataIndex: 'totalInitialQty', width: '15%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '审核时间', dataIndex: 'auditTime', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '12%', align: 'center' }
      ]
    }
  },
  methods: {
    loadWarehouseVal (con) {
      this.$set(this.form, 'warehouseSn', con || undefined)
    },
    // 选择退货仓库
    handleWarehouse (val) {
      this.form.warehouseSn = val
      this.chooseData = []
      if (this.salerReturnWsn && this.salerReturnWsn == val) {
        const cd = this.$store.state.app.tempBillOfData
        if (cd && this.$route.query.path == 'salerReturn') {
          this.chooseData.push(cd)
        } else {
          this.getReturnOrderList(this.salerReturnWsn)
        }
      }
    },
    custChange (val) {
      this.form.senderSn = val.key
      this.form.senderName = val.name
    },
    // 申请人员
    employeeChange (v, r) {
      this.$nextTick(() => {
        this.$refs.ruleForm.validateField(['applyPersonSn'])
      })
    },
    openSelModal () {
      this.showXtModal = true
    },
    closeModal () {
      this.openDepartUserModal = false
      this.showXtModal = false
      this.spinning = false
    },
    // 关联销售退货单
    getReturnOrderList (infoSn) {
      pickUpDetailQueryList({ pickUpSn: this.$route.params.sn, warehouseSn: infoSn }).then(res => {
        this.chooseData = []
        res.data.map(item => {
          this.chooseData.push(item.salesReturnBillEntity)
        })
      })
    },
    // 物流公司变动
    changeCompany (val) {
      const point = this.$refs.logisticsCompany.getPoint(val)
      this.$refs.logisticsPoint.getList(point)
      this.form.logisticsPoint = point[0]
    },
    //  详情
    async getDetail () {
      this.spinning = true
      this.disabled = true
      pickUpDetail({ pickUpSn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          const data = res.data
          if (!data.receiverName) {
            delete data.receiverName
          }
          this.form = Object.assign(this.form, data)
          // 获取附件列表
          this.form.attachmentList = ''
          this.attachList = res.data.attachmentList
          this.$refs.attachList.setFileList(this.attachList)
          // 发货方
          if (this.form.senderSn) {
            this.$refs.dealerSubareaScopeList.getDetail(this.form.senderSn)
          }
          // 物流点
          if (this.form.logisticsPoint) {
            const point = this.$refs.logisticsCompany.getPoint(this.form.logisticsCompany)
            this.$refs.logisticsPoint.getList(point)
          }
        } else {
          this.$refs.ruleForm.resetFields()
        }
        this.spinning = false
        this.disabled = false
      })
    },
    // 删除关联单
    handleDel (row) {
      const i = this.chooseData.findIndex(item => row.salesReturnBillNo == item.salesReturnBillNo)
      this.chooseData.splice(i, 1)
    },
    // 获取关联单sn列表
    getRtSnList () {
      const ret = []
      this.chooseData.map(item => {
        ret.push({ salesReturnSn: item.salesReturnBillSn, salesReturnNo: item.salesReturnBillNo })
      })
      return ret
    },
    // 提交
    handleSave (type) {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          form.attachmentList = _this.attachList
          form.pickUpSalesReturnList = this.getRtSnList()
          _this.spinning = true
          if (this.$route.params.sn) {
            delete form.warehouseName
          }
          pickUpSave(form).then(res => {
            if (res.status == 200) {
              // 保存
              if (type == 'save') {
                _this.$message.success(res.message)
                _this.$router.push({ name: 'billOfLadingList' })
                _this.spinning = false
              }
              // 提交
              if (type == 'submit') {
                pickUpDetail({ pickUpSn: res.data.pickUpSn })
                _this.openDepartUserModal = true
                _this.pickUpSn = res.data.pickUpSn
              }
            } else {
              _this.spinning = false
            }
          })
        } else {
          return false
        }
      })
    },
    // 提交信息
    handleSubmit (data) {
      this.spinning = true
      pickUpSubmit({ pickUpSn: this.$route.params.sn || this.pickUpSn, ...data }).then(res => {
        if (res.status == '200') {
          this.$message.success(res.message)
          this.$router.push({ name: 'billOfLadingList' })
        }
        this.spinning = false
      })
    },
    // 返回
    handleBack () {
      if (this.$route.query.path == 'salerReturn') {
        this.$router.push({ name: 'salesReturnList' })
      } else {
        this.$router.push({ name: 'billOfLadingList' })
      }
    },
    //  附件上传
    changeAttach (file) {
      this.attachList = JSON.parse(file)
      this.attachList.map(item => {
        item.fileType = item.extName
      })
    },
    resetForm () {
      this.form = {
        applyPersonSn: undefined, // 申请人
        applyPersonName: undefined,
        theme: '关于提货事宜', //  主题
        logisticsCompany: undefined, //  物流公司
        logisticsPoint: undefined, //  物流点
        senderName: '', //  发货方
        senderSn: '',
        receiverName: '', //  收货人
        receiverPhone: '', // 电话
        goodsNum: '', // 件数
        freight: '', // 运费
        remarks: '',
        attachmentList: '' // 附件
      }
      this.attachList = []
      this.$refs.attachList.setFileList('')
      this.$refs.ruleForm.resetFields()
    },
    pageInit () {
      this.resetForm()
      //  编辑页
      if (this.$route.params.sn) {
        this.form.theme = ''
        this.getDetail()
        this.salerReturnWsn = this.$route.params.wSn
        this.getReturnOrderList(this.$route.params.wSn)
      } else {
        this.chooseData = []
        // 从销售退货列表过来的数据
        const cd = this.$store.state.app.tempBillOfData
        if (cd && this.$route.query.path == 'salerReturn') {
          this.form.warehouseSn = cd.warehouseSn
          this.salerReturnWsn = cd.warehouseSn
          this.chooseData.push(cd)
        }
      }
      // 电话
      this.form.receiverPhone = this.$store.state.user.info && this.$store.state.user.info.mobile
    }
  },
  watch: {
    '$store.state.app.tempBillOfData' (newValue, oldValue) {
      this.pageInit()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .billOfLadingEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 52px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .billOfLadingEdit-cont{
      margin-bottom: 6px;
    }
    .affix{
      .ant-affix{
        z-index: 101;
      }
    }
  }
</style>
