<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"
                  @change="ltcChange"
                  v-model="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="收货人">
                <a-input
                  id="billOfLadingEdit-receiverName"
                  :maxLength="30"
                  v-model.trim="form.receiverName"
                  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
                  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="999999"
                  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="附件" 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">
              <a-form-model-item label="关联销退单" :label-col="{span:2}" :wrapper-col="{span:20}">
                <a-button type="link" @click="openSelModal">选择销退单</a-button>
                <div>
                  <a-table :columns="columns" :scroll="{ y: 400 }" :pagination="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>
                  </a-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"
        class="button-primary"
        :disabled="spinning"
        id="billOfLadingEdit-save-btn"
        size="large"
        @click="handleSave('save')"
        style="padding: 0 60px;">保存</a-button>
      <a-button
        type="primary"
        class="button-error"
        :disabled="spinning"
        id="billOfLadingEdit-submit-btn"
        size="large"
        @click="handleSave('submit')"
        style="padding: 0 60px;">提交</a-button>
    </div>
    <!-- 关联销退单 -->
    <selectXtModal
      ref="selXtModal"
      modalTit="选择销退单"
      :chooseData="chooseData"
      :openModal="showXtModal"
      @cancel="showXtModal=false"></selectXtModal>
    <!-- 选择审核人员 -->
    <chooseDepartUserModal :openModal="openDepartUserModal" @close="openDepartUserModal=false" @submit="handleSubmit"></chooseDepartUserModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect, 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 dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
export default {
  name: 'ProductInfoEdit',
  mixins: [commonMixin],
  components: { VSelect, Upload, STable, employee, dealerSubareaScopeList, chooseDepartUserModal, selectXtModal, logisticsCompany, logisticsPoint },
  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: '' // 附件
      },
      attachList: [],
      rules: {
        applyPersonSn: [
          { required: true, message: '请选择申请人', trigger: 'blur' }
        ],
        theme: [
          { required: true, message: '请输入主题', trigger: 'blur' }
        ]
      },
      chooseData: [],
      columns: [
        { title: '序号', scopedSlots: { customRender: 'no' }, width: '8%', 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: 'totalQty', 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: {
    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
    },
    ltcChange (v, row) {
      if (row) {
        this.$refs.logisticsPoint.getList(row.logisticsPointList)
        this.form.logisticsPoint = undefined
      }
    },
    // 关联销售退货单
    getReturnOrderList () {
      pickUpDetailQueryList({ pickUpSn: this.$route.params.sn }).then(res => {
        this.chooseData = []
        res.data.map(item => {
          this.chooseData.push(item.salesReturnBillEntity)
        })
      })
    },
    //  详情
    getDetail () {
      this.spinning = true
      this.disabled = true
      pickUpDetail({ pickUpSn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          const data = res.data
          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)
          }
        } 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, salesReturnBillNo: 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
          pickUpSave(form).then(res => {
            if (res.status == 200) {
              // 保存
              if (type == 'save') {
                _this.$message.success(res.message)
                _this.handleBack()
                _this.spinning = false
              }
              // 提交
              if (type == 'submit') {
                _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.handleBack()
        }
        this.spinning = false
      })
    },
    // 返回
    handleBack () {
      this.$router.push({ name: 'billOfLadingList' })
    },
    //  附件上传
    changeAttach (file) {
      this.attachList = JSON.parse(file)
      this.attachList.map(item => {
        item.fileType = item.extName
      })
    },
    pageInit () {
      this.attachList = []
      this.form.attachmentList = ''
      this.$refs.attachList.setFileList('')
      this.$refs.ruleForm.resetFields()
      if (this.$route.params.sn && this.$store.state.app.isNewTab) { //  编辑页
        this.form.theme = ''
        this.getDetail()
        this.getReturnOrderList()
      } else {
        // 新增
        // 如果是从销售退货列表过来的数据
        const cd = this.$store.state.app.tempBillOfData
        if (cd) {
          this.chooseData.push(cd)
        }
      }
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    this.chooseData = []
    this.pageInit()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

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