<!--
  @description: 发货订单管理-新增/发货编辑
  @author: 王俊楠
  @routerPath: /procurement/procurementOrderDeliverAdd
  @date： 2020-11-10 17:10:12
-->
<template>
  <div class="p0-16">
    <section class="title title_border">
      <i class="iconfont icon-fanhui pointer" @click="back()" />
      新增发货单
    </section>
    <div>
      <el-form ref="formData" :model="formData" :rules="formData.rules" :inline-message="true">
        <p class="page-title">
          1.发货单信息
        </p>
        <table class="from_table mb16">
          <tr>
            <td>
              <el-form-item ref="transportTool" label="运输工具" prop="transportTool" />
            </td>
            <td>
              <el-select v-model="formData.transportTool" filterable placeholder="请选择">
                <el-option
                  v-for="item in transport_toolList"
                  :key="item.typecode"
                  :label="item.typename"
                  :value="item.typecode"
                />
              </el-select>
            </td>
            <td>
              <el-form-item ref="logisticsCompany" label="物流公司" prop="logisticsCompany" />
            </td>
            <td>
              <gx-input
                v-model.trim="formData.logisticsCompany"
                gx-maxlength="varchar500"
              />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item label="发货联系人" prop="sendGoodsLinkerName" />
            </td>
            <td>
              <gx-input
                v-model.trim="formData.sendGoodsLinkerName"
                gx-maxlength="varchar20"
              />
            </td>
            <td>
              <el-form-item label="发货联系人手机号" prop="sendGoodsLinkerTel" />
            </td>
            <td>
              <gx-input
                v-model.trim="formData.sendGoodsLinkerTel"
                gx-maxlength="varchar20"
              />
            </td>
          </tr>
          <tr>
            <!-- <td>
              <el-form-item label="货物计量单位" prop="measuringUnit" />
            </td>
            <td>
              <el-select v-model="formData.measuringUnit" filterable placeholder="请选择">
                <el-option
                  v-for="item in purchaseUnitList"
                  :key="item.typecode"
                  :label="item.typename"
                  :value="item.typecode"
                />
              </el-select>
            </td> -->
            <td>
              <el-form-item ref="sendGoodsTime" label="发货日期" prop="sendGoodsTime" />
            </td>
            <td>
              <el-date-picker
                v-model="formData.sendGoodsTime"
                :format="elValueFormat"
                :value-format="elValueSaveFormat"
                :picker-options="pickerOptions0"
                type="datetime"
                placeholder="选择日期时间"
              />
            </td>
            <td>
              <el-form-item ref="logisticsSingleNumber" label="物流单号" prop="logisticsSingleNumber" />
            </td>
            <td>
              <gx-input
                v-model.trim="formData.logisticsSingleNumber	"
                gx-maxlength="varchar20"
              />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item ref="goodsName" label="货物名称" prop="goodsName" />
            </td>
            <td>
              <gx-input
                v-model.trim="formData.goodsName"
                gx-placeholder="placeholderText500"
                gx-maxlength="varchar50"
              />
            </td>
            <td>
              <el-form-item ref="measuringNum" label="重量(t)或体积（m³）" prop="measuringNum" />
            </td>
            <td>
              <gx-input
                v-model="formData.measuringNum"
                gx-placeholder="placeholderText500"
                gx-maxlength="varchar50"
              />
            </td>
          </tr>
          <tr>
            <!-- <td>
              <el-form-item ref="sendGoodsTime" label="发货日期" prop="sendGoodsTime" />
            </td>
            <td>
              <el-date-picker
                v-model="formData.sendGoodsTime"
                :format="elValueFormat"
                :value-format="elValueSaveFormat"
                type="datetime"
                placeholder="选择日期时间"
              />
            </td> -->
            <td>
              <!-- prop="remarks" -->
              <el-form-item ref="remarks" label="备注" />
            </td>
            <td colspan="3">
              <el-input
                v-model="formData.remarks"
                :autosize="{ minRows: 3, maxRows: 3 }"
                style="width:90%"
                type="textarea"
                maxlength="4000"
                show-word-limit
              />
            </td>
          </tr>
          <tr>
            <td>
              <el-form-item ref="sendGoodsRegion" label="联系地址" prop="sendGoodsRegion" />
            </td>
            <td colspan="3">
              <!--地区组件-->
              <cascader
                :region-text="formData.sendGoodsRegion"
                style="float: left;width:220px"
                @regionData="regionData"
              />
              <el-form-item prop="sendGoodsAddress" style="float: left;width:calc(100% - 270px)">
                <gx-input
                  v-model.trim="formData.sendGoodsAddress"
                  gx-placeholder="placeholderText1000"
                  gx-maxlength="varchar1000"
                />
              </el-form-item>
            </td>
          </tr>
        </table>
        <div class="clearfix offerInfo">
          <p class="fl page-title">
            2.货物信息
            <span style="color:red;font-size:12px">注：发货数量不能大于订单数量</span>
          </p>
        </div>
        <el-table :data="formData.tableData" border class="mb16 tableLimit clear-hint">
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column
            prop="lineItemNumber"
            header-align="center"
            align="center"
            min-width="150"
            label="订单号"
          />
          <el-table-column
            prop="productDescribe"
            header-align="center"
            align="left"
            min-width="200"
            label="物质信息"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.productDescribe }}</span>
            </template>
          </el-table-column>
          <el-table-column header-align="center" min-width="80" align="right">
            <template slot="header">
              <span>订单数量</span>
            </template>
            <template slot-scope="scope">
              <p>
                {{ scope.row.quantity }}
              </p>
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="left"
            min-width="220"
          >
            <template slot="header">
              <span class="red-star">*</span>
              <span>发货数量</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'tableData.' + scope.$index + '.sendGoodsNum'"
                :rules="formData.rules.sendGoodsNum"
              >
                <!-- <el-input
                  v-model.trim="scope.row.sendGoodsNum"
                  placeholder="发货数量"
                  gx-maxlength="varchar500"
                  size="mini"
                /> -->
                <money
                  :thousands="true"
                  :money-value="scope.row"
                  style="display: inline-block"
                  name="sendGoodsNum"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column header-align="center" align="center" min-width="280">
          <template slot="header" slot-scope="scope">
            <div class="deliveryDate">
              <span>预计到货时间</span>
            </div>
          </template>
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.goodsArrivalTime"
              :value-format="elValueFormatDate"
              type="date"
              placeholder="选择日期时间"
              size="mini"
            />
          </template>
        </el-table-column> -->
          <el-table-column
            prop="remarks"
            header-align="center"
            align="left"
            min-width="200"
            label="备注"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remarks"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="deliveryAdress"
            header-align="center"
            align="left"
            min-width="220"
            label="到货地址"
          />
          <el-table-column
            header-align="center"
            align="center"
            min-width="150"
            label="状态"
          >
            <template slot-scope="scope">
              {{ filterDictText(send_goods_detail_statusList,scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="230" fixed="right">
            <template slot-scope="scope">
              <!-- 00 待确认 01 待审核 03 已生效 -->
              <el-link
                v-if="scope.row.status === '01'"
                type="primary"
                @click.stop="cancelDeliveryFn(scope.row)"
              >
                [取消发货]
              </el-link>
              <el-link
                v-if="scope.row.status==='00'"
                type="primary"
                @click.stop="sureDeliveryFn(scope.row)"
              >
                [确认发货]
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <!--分页组件-->
      <pagination :pagination-data="paginationData" @change="loadData" />
      <!--操作按钮-->
      <div class="but_footer">
        <div class="but_footer-h">
          <div class="but_footer-but">
            <el-button
              :loading="confirmLoading"
              type="primary"
              @click.stop="sureDelivery('formData')"
            >
              提交
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/* api接口*/
import {
  listProcurementOrderProductPages,
  saveProcurementSendGoodsInfo, // 提交
  queryProcurementOrderInfo // 获取departId
} from '@/api/procurement/procurementOrder'
import { getUpdateDepartInfo } from '@/api/supplier/supplierBaseInfo' // 获取联系地址
/* 公共方法 */
import { filterDictText } from '@/assets/js/utils' // 字典code翻译中文
import { procurementOrderGroupMixins } from '@/views/procurement/procurementOrder/mixins/procurementOrderGroupMixins.js'
import { characters1_auto, phone, linkerName } from '@/assets/js/validate'// 校验输入内容

/*  公共组件 */
import { ListMixin } from '@/mixins/ListMixin' // 分页
import cascader from '@comp/common/cascader'// 地区三级联动
import pagination from '@comp/common/pagination/pagination' // 分页组件
import money from '@comp/common/money/money' // 金币组件

export default {
  name: 'ProcurementOrderCollectionAdd',
  components: {
    cascader, // 地区三级联动
    pagination, // 分页组件
    money
  },
  mixins: [procurementOrderGroupMixins, ListMixin],
  data() {
    return {
      pickerOptions0: {
        // 发货日期选择条件
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7// 如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
      formData: {
        goodsName: '', // 货物名称
        logisticsCompany: '', // 物流公司
        logisticsSingleNumber: '', // 货物单号
        measuringNum: '', // 重量(t)或体积(m³)
        // measuringUnit: '', // 货物计量单位 00重量/01体积
        remarks: '', // 备注
        sendGoodsAddress: '', // 发货详细地址
        sendGoodsLinkerName: '', // 发货联系人
        sendGoodsLinkerTel: '', // 发货联系人手机号
        sendGoodsRegion: '', // 发货地区
        sendGoodsTime: '', // 发货日期
        transportTool: '', // 运输工具 00火车/01货车/02飞机/03轮船/04第三方物流
        orderId: this.$route.params.orderId, // 订单id
        tableData: [], // 行项目信息
        rules: {
          transportTool: [{ required: true, validator: characters1_auto, trigger: 'change' }], // 运输工具
          logisticsCompany: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 物流公司
          sendGoodsLinkerName: [{ required: true, validator: linkerName, trigger: 'blur' }], // 联系人
          sendGoodsLinkerTel: [{ required: true, validator: phone, trigger: 'blur' }], // 发货联系人手机号
          measuringUnit: [{ required: true, validator: characters1_auto, trigger: 'change' }], // 货物计量单位
          logisticsSingleNumber: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 物流单号
          goodsName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 货物名称
          measuringNum: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 重量(t)或体积（m³）
          sendGoodsTime: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 发货日期
          remarks: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 备注
          sendGoodsRegion: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 联系地址
          sendGoodsAddress: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 详细地址
          sendGoodsNum: [{ required: true, validator: (rule, value, callback) => {
            const index = rule.field.indexOf('.') + 1
            const $index = rule.field.slice(index, 11)
            if (!value && value !== 0) {
              return callback(new Error('不能为空!'))
            }
            if (Number(value) > Number(this.formData.tableData[$index].quantity)) {
              return callback(new Error('发货数量不能大于订单数量!'))
            }
            callback()
          }, trigger: 'blur' }]
        }
      },
      transportList: [], // 运输工具
      purchaseUnitList: [], // 计量单位
      confirmLoading: false
      // 校验输入内容

    }
  },
  computed: {
  },
  watch: {
  },
  created() {
    this.loadData()
  },
  methods: {
    filterDictText, // 字典code翻译中文
    // 新增发货三级联动组件使用
    regionData(regionName, location) {
      // this.formData.sendGoodsRegionName = regionName
      // this.formData.sendGoodsRegion = location.join(',')
      this.formData.sendGoodsRegion = regionName
    },
    // 返回发货订单处理页面
    back() {
      this.$router.push({
        path: 'procurementOrderDeliverHandleAdd'
      })
    },
    // 获取数据
    loadData() {
      const params = {
        orderId: this.formData.orderId,
        pageNo: this.paginationData.pageNo,
        pageSize: this.paginationData.pageSize
        // const params = {
        //   sendGoodsDetailInfoLists: this.tableData,
        //   ...this.formData
        // }
      }
      // 获取联系地址参数
      const paramsData = {
        departId: ''
      }
      // 获取departId
      queryProcurementOrderInfo({ orderId: params.orderId }).then((res) => {
        paramsData.departId = res.winningDepartId
      })
      // 获取联系地址
      getUpdateDepartInfo(paramsData).then((res) => {
        this.formData.sendGoodsRegion = res.data.info.areaValue
        this.formData.sendGoodsAddress = res.data.info.address
      })
      listProcurementOrderProductPages(params).then(response => {
        this.loading = false
        this.paginationData.total = response.data.total
        const list = response.data.records
        this.formData.tableData = list.map((item) => {
          return {
            lineItemNumber: item.lineItemNumber, // 行项目编号
            productDescribe: item.productDescribe, // 物资描述
            quantity: item.quantity, // 订单数量
            remarks: '', // 备注
            // goodsArrivalTime: '', // 预计到货时间
            sendGoodsNum: '', // 发货数量
            id: item.id, // id
            deliveryAdress: item.deliveryAdress, // 到货地址
            status: '00' // 状态 00待发货/01已发货
          }
        })
      }).catch(() => {
      })
    },
    // 提交时校验 发货数量不能大于订单数量
    // verifyAmountList() {
    //   let verifyAmount = true
    //   this.formData.tableData.map(item => {
    //     if (Number(item.sendGoodsNum) > Number(item.quantity)) {
    //       this.$message({
    //         type: 'warning',
    //         message: '发货数量不能大于订单数量'
    //       })
    //       verifyAmount = false
    //     }
    //     if (item.sendGoodsNum === null || item.sendGoodsNum === '') {
    //       this.$message({
    //         type: 'warning',
    //         message: '发货数量不能为空'
    //       })
    //       verifyAmount = false
    //     }
    //   })
    //   return verifyAmount
    // },
    // 发货
    sureDelivery(formName) {
      // const verifyAmountList = this.verifyAmountList()
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const listData = this.formData.tableData.reduce((arr, pre) => {
            if (pre.status === '01') {
              arr.push(pre)
            }
            return arr
          }, [])
          const params = {
            sendGoodsDetailInfoLists: listData,
            ...this.formData
          }
          delete params.tableData
          delete params.rules
          if (listData.length === this.formData.tableData.length) {
            saveProcurementSendGoodsInfo(params).then((res) => {
              this.back() // 跳转
            })
          } else {
            this.$message.warning('请确认发货')
          }
        } else {
          this.$message.warning('请注意页面提示信息！')
        }
      })
    },
    // 表格确认发货
    sureDeliveryFn(row) {
      row.status = '01'
    },
    // 取消发货
    cancelDeliveryFn(row) {
      row.status = '00'
    }
  }
}
</script>

<style lang="less" scoped>
.clear-hint {
  /deep/.el-form-item--small .el-form-item__error {
    display: none;
  }
  /deep/ .el-form-item.el-form-item--small {
    margin-bottom: 0px;
  }
}
</style>

