<template>
  <div class="app-container">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="left"
      inline
      :key="$route.fullPath"
      :validate-on-rule-change="false"
    >
      <div class="page-title">{{ editMode ? $t('编辑包裹') + '-' + (form.consNum) : (signedMode?$t('签收包裹') + '-' + (form.consNum):$t('新建包裹')) }}</div>
      <el-card class="form-section mt-10">
        <el-form-item :label="$t('集运仓库')" v-model="form.wareId" prop="wareId" :rules="{
                              required: true, message: '请选择集运仓库', trigger: 'blur'
                              }">
          <template v-for="(item, index) in warehouseList">
            <el-button :type="warehouseList.length === 1 ||form.wareId === item.id ? 'primary' : 'default'"
                       @click="setWarehouseId(item)">
              {{ item.titleZh }}
            </el-button>
          </template>
        </el-form-item>
      </el-card>
      <el-card class="form-section mt-10">
        <template #header>
          <div slot="header" class="card-title">发货人</div>
        </template>
        <el-form-item :label="$t('客户编号：')" prop="customerNumber">
          <!-- <customer-contact-selector v-model="form.consignorContactsId" @change="consignorContact = $event" type="1" /> -->
          <div class="contact">
            <el-input v-model="form.customerNumber" placeholder=""/>
            <img disabled src="@/assets/svg/contacts.svg" class="phonebook"
                 @click="contactChooseType='consignor'"/>
            <img src="@/assets/svg/contact_create.svg" class="phonebook"
                 @click="quickCreateType='0'"/>
          </div>
        </el-form-item>
        <el-form-item :label="$t('电话')" prop="consignorPhone">
          <div class="flex">
            <area-code-selector v-model="form.areaCode" class="w-200 mr-10" disabled/>
            <el-input v-model="form.phoneNew" class="w-200" disabled/>
          </div>
        </el-form-item>
      </el-card>
      <el-card class="mt-10">
        <div slot="header" class="card-title">{{ $t('运输') }}</div>
        <div class="form-section">
          <el-form-item :label="$t('运输方式')" prop="transportId">
            <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="form.transportId" formatter="number"
                           clearable @input="updateRoutes('transportId')"/>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('始发城市')" prop="departureId" :disabled="false">
            <el-select v-model="form.departureId" :placeholder="$t('请选择始发地')" :disabled="form.shipmentState > 0"
                       clearable @input="updateRoutes('departureId')">
              <el-option v-for="item in exportCityList" :label="$l(item, 'title')" :value="item.id"
                         :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('目的国家')" prop="consigneeCountryId">
            <el-select v-model="form.consigneeCountryId" :placeholder="$t('请选择目的国家')"
                       @change="handleChangeDestCountry" clearable :disabled="form.shipmentState > 0">
              <el-option v-for="item in showDestCountryList" :label="$l(item, 'guojiaName')" :value="item.guojia"
                         :key="item.guojia"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('目的城市')" prop="consigneeCityId">
            <el-select v-model="form.consigneeCityId" :placeholder="$t('请选择目的地')" @change="handleChangeDestCity"
                       clearable>
              <el-option v-for="item in showDestCityList" :label="$l(item, 'shiName')" :value="item.shi"
                         :key="item.shi"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('选择线路')" prop="lineId">
            <el-input
              :value="selectedRouter ? $l(selectedRouter, 'startTitle') + ' > ' + $l(selectedRouter, 'destTitle') : ''"
              disabled :placeholder="$t('请在右侧选择线路')"></el-input>
          </el-form-item>
          <!--select是原生组件，不受el-form的disabled控制-->
          <select size="5" v-model="form.warehouseLineId"
                  style="min-width: 300px; border:1px solid #DCDFE6; border-radius:4px"
                  @change="handleChangeLineId">
            <option v-for="item in routerList" :value="item.id" :key="item.id">
              {{ $l(item, 'startTitle') }} >> {{ $l(item, 'destTitle') }}
              (
              <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="item.transportType"></dict-tag>
              )
            </option>
          </select>
        </div>
      </el-card>
      <el-card class="form-section mt-10">
        <div slot="header" class="card-title">{{ $t('快递') }}</div>
        <div class="form-section">
          <el-form-item :label="$t('快递单号')" :rules="{
                              required: true, message: '请填写完整的快递单号包括字母', trigger: 'blur'
                              }">
            <el-input v-model="form.expressNo" :placeholder="$t('请输入购买商品的快递单号')" :disabled="false">
              <el-button type="primary" slot="append" @click="getConsCourierNumber">
                {{ $t('生成单号') }}
              </el-button>
            </el-input>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('快递公司')">
            <el-select v-model="form.expressId" :placeholder="$t('请选择快递公司')">
              <el-option v-for="nodeItem in expressList" :key="nodeItem.id" :label="nodeItem.companyName"
                         :value="nodeItem.id"/>
            </el-select>
          </el-form-item>
        </div>
      </el-card>
      <el-card class="form-section mt-10">
        <div slot="header" class="card-title">
          <!--lanbm 根据需求文档改 商品信息 为 商品 -->
          <div class="card-name">{{ $t('商品') }}</div>
        </div>
        <el-table :data="form.consItemVOList" border class="product-list">
          <el-table-column :label="$t('序号')" width="60px" fixed>
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('中文品名')">
            <template slot="header" slot-scope="scope">
              {{ $t('中文品名') }} <span class="red">*</span>
            </template>
            <template slot-scope="scope">
              <el-form-item label=""
                            :prop2="`consItemVOList.${scope.$index}.prodId`"
                            :rules2="{
                        }"
                            class="mb-0 mr-0"
              >
                <product-selector
                  v-model="scope.row.prodId"
                  @change="onProductChange(scope.row, $event)"
                  @focus="scope.row.updated = true"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="`${$t('数量')}(${$t('个')})`">
            <template slot-scope="{row}">
              <el-input-number :min="1" :step="1" style="width: 80px;" :controls="false" v-model="row.quantity"
              />
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" width="80px" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="delProduct(scope.$index)">{{ $t('删除') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex space-between mt-10">
          <div>{{ $t('登记总数量') }}：{{ sum.totalQuatity.toFixed() || 0 }}</div>
          <el-button type="primary" size="mini" @click="addProduct(null)">{{ $t('添加') }}
          </el-button>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('订单总货值(元)')" prop="worth" :rules="{
                              required: true, message: '填写订单人民币总货值', trigger: 'blur'
                              }">
            <el-input v-model="form.worth" required :placeholder="$t('请输入购买商品的总货值')" :disabled="false">
            </el-input>
          </el-form-item>
        </div>
        <div class="form-section">
          <el-form-item :label="$t('包裹备注')" prop="remarks" class="w-500">
            <el-input v-model="form.remarks" type="textarea"></el-input>
          </el-form-item>
        </div>
        <div class="form-section" v-if="signedMode">
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('签收人')">
                <el-select v-model="form.signer">
                  <el-option v-for="item in allSimplList" :key="item.id" :label="item.nickname"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('签收时间')">
                <el-date-picker v-model="form.signedTime" type="datetime" value-format="timestamp"></el-date-picker>
              </el-form-item>
            </el-col>

          </el-row>
        </div>
      </el-card>
      <el-card class="form-section mt-10" v-if="signedMode">
        <div slot="header" class="card-title1">{{ $t('签收图片') }}</div>
        <el-form-item prop="mediaUrl">
          <image-upload v-model="form.mediaUrl"/>
        </el-form-item>
      </el-card>
    </el-form>
    <el-button type="primary" @click="submitForm(0)" v-if="copyMode||(!editMode&&!signedMode)">{{ $t('添加包裹') }}</el-button><!--草稿-->
    <el-button type="primary" @click="submitForm(1)" v-if="!copyMode&&editMode">{{ $t('保存') }}</el-button><!--草稿-->
    <el-button type="primary" @click="submitForm(1)" v-if="signedMode">{{ $t('确认签收') }}</el-button><!--草稿-->
    <el-button @click="$store.dispatch('tagsView/delCurrentView')">{{ $t('取消') }}</el-button>
    <choose-contact-dialog v-if="!!contactChooseType" :type="2" @choose="onContactChoose"
                           @close="contactChooseType=null"/>
    <quick-create-customer v-if="quickCreateType" :type="quickCreateType" @success="onContactChoose"
                           @close="quickCreateType=null"/>
  </div>
</template>

<script>
import {
  getConsWarehouse,
  getGuojiaAndShiAndWarehouseList,
  openedRouterList as getOpenedRouterList
} from '@/api/ecw/warehouse'
import AreaCodeSelector from "@/components/AreaCodeSelector/index.vue";
import ChooseContactDialog from "@/components/ChooseContactDialog/index.vue";
import QuickCreateCustomer from "@/components/QuickCreateCustomer/index.vue";
import Selector from "@/components/Selector/index.vue";
import {getTradeCityList} from "@/api/ecw/region";
import {createCons, getCons, getConsCourierNumber, updateCons} from "@/api/ecw/cons";
import {getExpressPage} from "@/api/ecw/express";
import Template from "@/views/cms/template/index.vue";
import ProductSelector from "@/components/ProductSelector/index.vue";
import Decimal from "decimal.js";
import ImageUpload from "@/components/ImageUpload/index.vue";
import {listAllSimpl} from "@/api/system/user";


export default {
  name: "EcwConsEdit",
  props: {
    more:Boolean // 标识多个预报
  },
  components: {
    ImageUpload,
    ProductSelector,
    Template,
    Selector,
    QuickCreateCustomer,
    ChooseContactDialog,
    AreaCodeSelector
  },
  data() {
    return {
      // 表单参数
      form: {
        consItemVOList: [],
      },
      isUpdate:false,
      rules: {},
      warehouseList: [],
      tradeCityList: [],
      contactChooseType: null, // 联系人选择对象consignor(发货人) 或者 consignee（收货人）
      quickCreateType: null, // 快速新建客户类型，1发货人，2收货人
      destCountryList: [],
      showDestCityList: [],
      selectedRouter: null,
      routerList: [],
      expressList: [],
      allSimplList: [],
    }
  },
  watch: {
    'form.wareId'(val) {
      this.form.departureId=this.warehouseList.find(item => item.id === val).shi
      this.getOpenedRouterList()
    },
  },
  computed: {
    sum() {
      let sum = {
        totalNum: new Decimal(0),
        totalVolume: new Decimal(0),
        totalWeight: new Decimal(0),
        totalWorth: new Decimal(0),
        totalQuatity: new Decimal(0)
      }
      if (!this.form || !this.form.consItemVOList) return sum
      this.form.consItemVOList.forEach(item => {
        sum.totalNum = sum.totalNum.plus(item.num || 0)
        sum.totalVolume = sum.totalVolume.plus(item.volume || 0)
        sum.totalWeight = sum.totalWeight.plus(item.weight || 0)
        sum.totalWorth = sum.totalWorth.plus(item.worth || 0)
        sum.totalQuatity = sum.totalQuatity.plus(item.quantity || 0)
      })
      return sum
    },
    importCityIds() {
      let ids = []
      this.destCityList.forEach(item => {
        ids.push(item.shi)
      })
      return ids
    },
    importCountryIds() {
      let ids = []
      this.destCountryList.forEach(item => {
        ids.push(item.guojia)
      })
      return ids
    },
    exportCityIds() {
      let ids = []
      this.exportCityList.forEach(item => {
        ids.push(item.id)
      })
      return ids
    },
    showDestCountryList() {
      return this.destCountryList
    },
    // 是否编辑
    editMode() {
      return this.$route.path.indexOf('edit') > 0
    },
    signedMode() {
      return this.$route.path.indexOf('sign') > 0;
    },
    copyMode() {
      return this.$route.query.copy && this.$route.query.copy == 1;
    },
    exportCityList() {
      console.log("this.tradeCityList", this.tradeCityList)
      return this.tradeCityList.filter(item => item.type == 2 || item.type == 3)
    },
  },
  async created() {
    listAllSimpl().then((r) => {
      this.allSimplList = r.data
    })
    this.getExpressList()
    await getGuojiaAndShiAndWarehouseList({tradeType: 1}).then(({data}) => {
      this.destCountryList = data.guojiaList
      this.destCityList = data.shiList
      this.showDestCityList = data.shiList
    })
    getConsWarehouse().then((r) => {
      this.warehouseList = r.data;
      if (this.warehouseList.length === 1) {
        this.setWarehouseId(this.warehouseList[0]);
      }
    });
    await this.getTradeCity()
    this.addProduct()
    if (this.$route.query.id) {
      console.log('created 加载订单数据')
      this.isUpdate=true
      this.getCons()
    }
  },
  methods: {
    getCons(){
      getCons(this.$route.query.id).then(res => {
        this.form = res.data
          if (this.$route.query.copy && this.$route.query.copy == 1) {
            this.form.consId = null
            this.form.consNo = null
            this.form.expressNo=null
            this.form.orderId=null
            this.form.inspectStatus=null
            this.form.inspectRemark=null
            this.form.signStatus=null
            this.form.signedTime=null
            this.form.signedRemarks=null
            this.form.signer=null
            this.form.consItemVOList.forEach(item => {
              item.id = null
              item.consId = null
              item.consItemId = null
            })
          }
      })
    },
    submitForm(val) {
      this.form.sumQuantity = Number(this.sum.totalQuatity.toFixed())
      this.$refs["form"].validate(async (valid, errors) => {
        let isInclude = false
        this.form.consItemVOList.map(item => {
          //如果商品特性包含不接受货物，不能创建订单或修改订单
          if (item.prodAttrArr.indexOf(4) != -1) {
            isInclude = true
          }
          item.prodAttrIds = item.prodAttrArr.join(',')
        })
        if (isInclude) {
          return this.$notify({
            title: this.$t('提示'),
            message: this.$t("订单包含不接受货物，请检查"),
            type: 'warning'
          });
        }
        for (const i in this.form.consItemVOList) {
          const item = this.form.consItemVOList[i]
          if (!item.prodId) {
            return this.$message.error(this.$t(`第${Number(i) + 1}行未选择商品`, i + 1))
          }
        }
        //如果客户编号为空，返回错误提示
        if (!this.form.customerNumber) {
          return this.$message.error(this.$t(`请选择客户`))
        }
        if (!(this.form.transportId||this.form.consigneeCityId)){
          return this.$message.error(this.$t(`请选择运输方式或目的城市`))
        }
      })
      //货值要大于等于10，不大于10的要弹窗提示，左侧是忽略继续提交右侧按钮时前去检查
      if (this.form.worth <= 10) {
        return this.$confirm(this.$t('货值需要大于等于10，请检查'), this.$t('提示'), {
          confirmButtonText: this.$t('忽略继续提交'),
          cancelButtonText: this.$t('前去检查'),
          type: 'warning'
        }).then(() => {
          if (val===0){
            this.createCons()
          }else {
            this.updateCons()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('已取消提交')
          });
        });
      }else {
        if (val===0){
          this.createCons()
        }else {
          this.updateCons()
        }
      }

    },
    updateCons() {
      updateCons(this.form).then(res => {
        if (res.code === 0){
          if (this.signedMode){
            this.$modal.msgSuccess(this.$t("签收成功"));
          }else {
            this.$modal.msgSuccess(this.$t("修改成功"));
          }
          this.$router.back()
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    createCons() {
      createCons(this.form).then(res => {
        if (res.code === 0) {
          this.$message.success(this.$t('创建成功'))
          if (this.more) {
            this.resetByMore()
          } else {
            if (this.copyMode){
              this.$redirect('cons/success?consId=' + res.data)
            }else{
              this.$redirect('success?consId=' + res.data)
            }
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    resetByMore(){
      const oldForm=this.form
      this.form={
        consItemVOList: [],
        wareId: oldForm.wareId,
        customerNumber: '',
        phoneNew: '',
        areaCode: '',
        transportId: oldForm.transportId,
        departureId: null,
        consigneeCountryId: oldForm.consigneeCountryId,
        consigneeCityId: oldForm.consigneeCityId,
        warehouseLineId: oldForm.warehouseLineId,
        expressNo: '',
        expressId: null,
        worth: '',
        remarks: '',
        mediaUrl: []
      }
      this.addProduct()
    },
    // 删除一条产品
    delProduct(index) {
      this.$confirm(this.$t('确定删除此条内容么？'))
        .then(res => {
          this.form.consItemVOList.splice(index, 1)
        })
    },
    addProduct(data) {
      this.form.consItemVOList.push(data || {
        prodAttrArr: [],
        prodId: null,
        worth: undefined,
        volume: '',
        weight: '',
        num: undefined
      })
    },
    onProductChange(row, product) {
      console.log(product)
      // 如果是清除商品
      if (!product) {
        row.fee = null
        row.prodAttrArr = []
        return false
      }
      // 没有orderItemId则表示新增的，否则就是编辑回显的
      // row.updated 表示用户操作了,用来区分是自动回显还是用户选择商品
      if (!row.orderItemId || row.updated) {
        row.prodAttrArr = !product ? [] : product.attrId.split(',').filter(item => item !== '').map(item => +item)
      }
      row.prodTitleEn = product.titleEn
      row.prodTitleZh = product.titleZh
    },
    getExpressList() {
      let params = {
        pageNo: 1,
        pageSize: 1000
      }
      getExpressPage(params).then((res) => {
        this.expressList = res.data.list
      })
    },
    // 生成快递单号
    getConsCourierNumber() {
      getConsCourierNumber().then(res => {
        this.$set(this.form, 'expressNo', res.data)
      })
    },
    async getTradeCity(a) {
      let query = {}
      if (this.form.channelId) {
        query.channelId = this.form.channelId
      }
      this.tradeCityList = (await getTradeCityList(query)).data
    },
    // 切换线路回调
    async handleChangeLineId() {
      await this.$nextTick()
      this.selectedRouter = this.routerList.find(item => item.id === this.form.warehouseLineId)
      console.log("handleChangeLineId",
        "路线", this.form.warehouseLineId,
        "目的市", this.selectedRouter?.destCityId,
        "目的国", this.selectedRouter?.destCountryId,
        "始发市", this.selectedRouter?.startCityId)
      if (this.form.warehouseLineId) {
        this.form.consigneeCityId = this.selectedRouter?.destCityId
        this.form.consigneeCountryId = this.selectedRouter?.destCountryId
        this.form.departureId = this.selectedRouter?.startCityId
        this.form.consigneeWarehouseId = this.selectedRouter?.destWarehouseId
      }
    },
    // 切换目的国
    handleChangeDestCountry(val) {
      console.log("handleChangeDestCountry", val)
      // 目的城市赋值
      this.form.consigneeCountryId = val
      if (!val) {
        this.showDestCityList = JSON.parse(JSON.stringify(this.destCityList))
      } else {
        this.showDestCityList = JSON.parse(JSON.stringify(this.destCityList.filter(item => item.guojia === val)))
      }
      if (this.form.consigneeCountryId) {
        this.form.consigneeCityId = null
        this.form.warehouseLineId = null
        this.selectedRouter = null
        this.updateRoutes('handleChangeDestCountry')
      }
    },
    // 切换目的城市
    async handleChangeDestCity(val) {
      this.form.consigneeCityId = val
      if (this.form.consigneeCityId) {
        this.form.warehouseLineId = null
        this.selectedRouter = null
        this.form.consigneeCountryId = this.destCityList.find(item => item.shi === val)?.guojia

      }
      await this.updateRoutes('handleChangeDestCity')
    },
    onContactChoose(contact) {
      console.log('选择联系人', contact)
      if (!this.contactChooseType && !this.quickCreateType) return
      if (!this.contactChooseType && this.quickCreateType) {
        this.contactChooseType = this.quickCreateType == 0 ? 'consignor' : 'consignee'
      }
      this.$set(this.form, 'customerNumber', contact.customerNumber)
      this.$set(this.form, 'customerId', contact.customerId)
      this.$set(this.form, 'areaCode', contact.areaCode.replace('+', ''))
      this.$set(this.form, 'phoneNew', contact.phoneNew)
      if (this.contactChooseType == 'consignor') {
        this.noConsignee = contact.noConsignee
      }
      this.contactChooseType = null
      this.quickCreateType = null
    },
    setWarehouseId(item) {
      this.$set(this.form, 'wareId', item.id)
    },
    // 更新路线并打印来源
    updateRoutes(fr) {
      console.log("%cupdateRotutes", "color: blue", fr)
      return this.getOpenedRouterList()
    },
    // 获取路线
    async getOpenedRouterList() {
      let params = {}
      if (this.form.departureId) {
        params.startCityId = this.form.departureId
      }
      if (this.form.consigneeCountryId) {
        params.destCountryId = this.form.consigneeCountryId
      }
      if (this.form.consigneeCityId) {
        params.destCityId = this.form.consigneeCityId
      }
      if (this.form.transportId) {
        params.transportType = this.form.transportId
      }
      if (this.form.channelId) {
        params.channelId = this.form.channelId
      }
      console.log("获取路线,参数", params)
      // 始发，目的和运输方式都没有的时候不获取
      if (!params.startCityId && !params.destCountryId && !params.destCityId && !params.transportType) return false
      return getOpenedRouterList(params).then(res => {
        this.routerList = res.data.filter(item => {
          return this.exportCityIds.indexOf(item.startCityId) > -1 && this.importCountryIds.indexOf(item.destCountryId) > -1 && (this.importCityIds && this.importCityIds.indexOf(item.destCityId) > -1)
        })
        console.log(`已获取到路线${res.data?.length}条，有效路线${this.routerList.length}条,参数:${JSON.stringify(params)}`)
        console.table([
          {
            all: res.data.map(item => item.id).join(","),
            avail: this.routerList.map(item => item.id).join(",")
          }
        ])
        // 如果已选择的线路ID不在上述路线列表里则重置
        if (this.form.warehouseLineId) {
          this.selectedRouter = this.routerList.find(item => item.id == this.form.warehouseLineId)
          if (!this.selectedRouter) {
            console.log(`获取到的路线未找到原路线lineId: ${this.form.warehouseLineId}，重置为null`)
            this.$set(this.form, 'warehouseLineId', null)
          }
        }
      })
    },
  }
}

</script>

<style lang="scss" scoped>
.w-380 {
  width: 380px;
}

.space-between {
  justify-content: space-between;
  margin-right: 12px;
}

.justify-end {
  justify-content: flex-end;
}

.card-title {
  font-size: 18px;
  display: flex;

  .card-name {
    flex: 1;
  }
}

.card-title1 {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  justify-content: center;

  .card-name {
    flex: 1;
  }
}

.form-section {
  .contact {
    display: flex;
    align-items: center;

    img.phonebook {
      width: 30px;
      height: 30px;
      margin-left: 10px;
      cursor: pointer;
    }
  }

}

::v-deep .product-list .el-form-item__error {
  position: static;
}

::v-deep th.el-table__cell .cell {
  white-space: nowrap;

  .red {
    color: red;
  }
}

::v-deep .right-label {
  .el-form-item__label {
    width: 150px;
    display: inline-flex;
    justify-content: flex-end;
    align-items: center;
  }
}
</style>
