<!--批量加价-->
<template>
  <div class="app-container">
    <div class="page-title">{{$t('批量加价')}}</div>
    <div>
        {{$t('运费或全包加价')}}
        <!--货币-->
        <selector :disabled="approval" v-model="form.freightCurrencyId" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable class="w-100 ml-10" />
        <!--金额-->
        <el-input :disabled="approval" type="number" v-model="form.freightFee" :min="1"  @keyup.native="checkPositive(form, 'freightFee')"  class="w-100 ml-10" />
        <!--单位-->
        <selector :disabled="approval" v-model="form.freightUnitId" :options="unitList" :label-field="$l('title')" value-field="id" defaultable  class="w-100 ml-10" />
    </div>
    <div class="mt-10">
        {{$t('清关费加价')}}
        <!--货币-->
        <selector  :disabled="approval" v-model="form.clearanceCurrencyId" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable  class="w-100 ml-10" />
        <!--金额-->
        <el-input  :disabled="approval" type="number" v-model="form.clearanceFee" :min="1"  @keyup.native="checkPositive(form, 'clearanceFee')"  class="w-100 ml-10" />
        <!--单位-->
        <selector  :disabled="approval" v-model="form.clearanceUnitId" :options="unitList" :label-field="$l('title')" value-field="id" defaultable  class="w-100 ml-10" />
        <span>*{{$t('若线路价格为全包价，输入清关费不生效')}}</span>
    </div>

    <el-card class="mt-20" v-if="shipmentObj">
      <el-descriptions :column="4" border>
        <el-descriptions-item :label="$t('自编号')">
          {{shipmentObj.selfNo}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('运输方式')">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="shipmentObj.transportType" />
        </el-descriptions-item>
        <!-- <el-descriptions-item :label="$t('出货渠道')">
          {{getShipChannelName(shipmentObj.shippingChannelId)}}
        </el-descriptions-item> -->
        <el-descriptions-item :label="$t('柜型')">
          {{getCabinetLabel(shipmentObj.cabinetId)}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('状态')">
          {{shipmentObj.shipmentStatusText}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('总计')">
          {{getBoxSum(shipmentObj.boxStatistics)}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('始发地')">
          {{getCityName(shipmentObj.startWarehouseId)}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('目的地')">
          {{getCityName(shipmentObj.destWarehouseId)}}
        </el-descriptions-item>
        <el-descriptions-item label="SO NO">
          {{shipmentObj.bookSeaInfo ? shipmentObj.bookSeaInfo.sono : '' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="mt-20">
      <div slot="header">
        {{$t('明细')}}
      </div>
      <div class="flex-row" style="display: flex">
        <div class="flex-1">
          {{$t('当前部分')}}：
          <el-select :placeholder="$t('请选择')" v-model="sectionId" @change="sectionChange">
            <el-option key="0" :label="$t('全部')" :value="0"></el-option>
            <el-option v-for="item in sectionList" :key="item.id" :label="item.title" :value="item.id"></el-option>
          </el-select>
        </div>
        <div class="document-status" v-if="sectionObj">
          <span>{{$t('单证状态')}}：</span>
          <template v-for="(item, index) in getDocStatus(sectionObj.sectionOrderList)">
            <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="item" :key="index" class="document" />
          </template>
        </div>
      </div>
      <el-table v-if="sectionObj" ref="orderTable" border :data="sectionObj.sectionOrderList || []" @selection-change="handleSelectionChange" class="mt-10">
        <el-table-column type="selection" width="50"></el-table-column>>
        <el-table-column align="center" :label="$t('序号')" width="50" prop="tidanNum" />
        <el-table-column prop="orderNo" :label="$t('订单号')" align="center">
          <template v-slot="scope">
            <a href="javascript:void(0)" @click="jumpOrderDetail(scope.row)">{{ scope.row.orderNo }}</a>
          </template>
        </el-table-column>
        <el-table-column prop="goodsList" :label="$t('货物信息')" width="230px" align="center">
          <template v-slot="{row}">
            <section>
              <div v-for="(item, index) in row.goodsList" :key="index">
                <div>{{index+1}}：{{$l(item, 'prodTitle')}}</div>
              </div>
            </section>
          </template>
        </el-table-column>
        <el-table-column prop="num" :label="$t('计划箱数')" align="center"></el-table-column>
        <el-table-column prop="installNum" :label="$t('实装箱数')" align="center"></el-table-column>
        <el-table-column prop="unloadNum" :label="$t('卸柜箱数')" align="center"></el-table-column>
        <el-table-column prop="destWarehouseName" :label="$t('提货点')" align="center"></el-table-column>
        <el-table-column prop="volume" :label="$t('体积')" align="center"></el-table-column>
        <el-table-column prop="weight" :label="$t('重量')" align="center"></el-table-column>
        <el-table-column prop="totalWorth" :label="$t('货值')" align="center"></el-table-column>
        <el-table-column prop="customsType" :label="$t('报关方式')" align="center">
          <template slot-scope="scope">
            <div :class="scope.row.customsType !== 1 ? 'customsType-red' : ''">
              <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="scope.row.customsType" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="customsFee" :label="$t('报关费用')" align="center"></el-table-column>
        <el-table-column prop="" :label="$t('加价单价')" align="center" width="200px">
          <template slot-scope="scope">
            <div>
              {{$t('运费')}}：{{form.freightFee || 0}}{{ currencyMap[form.freightCurrencyId]}}/{{unitMap[form.freightUnitId]}}
            </div>
            <div>
              {{$t('清关费')}}：{{form.clearanceFee || 0}}{{ currencyMap[form.clearanceCurrencyId]}}/{{unitMap[form.clearanceUnitId]}}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="mt-20">
      <work-flow xmlkey="shipment_batch_add_price" v-model="form.copyUserId" :disabled="approval"></work-flow>
    </el-card>

    <div class="mt-20" v-if="shipmentObj">

      <template v-if="approval">
        <el-button type="primary" @click="$router.push('/bpm/process-instance/detail?id=' + shipmentObj.batchAddPriceApprovalInfo.bpmProcessId)">{{$t('加价申请审核中')}}</el-button>
        <el-button type="default" @click="cancelAproval">{{$t('取消审核')}}</el-button>
      </template>
      <template v-else>
        <el-button type="primary" @click="submit">{{$t('提交审核')}}</el-button>
      </template>
      <el-button type="default" @click="$store.dispatch('tagsView/delCurrentView')">{{$t('返回')}}</el-button>
    </div>
  </div>
</template>

<script>
import {getCurrencyList} from "@/api/ecw/currency";
import {getUnitList} from "@/api/ecw/unit";
import selector from '@/components/Selector'
import {getChannelList} from "@/api/ecw/channel";
import {getCabinetPage} from "@/api/ecw/cabinet";
import {getWarehouseList} from "@/api/ecw/warehouse";
import {getSupplierPage} from "@/api/ecw/supplier";
import {approvalCancel, boxGoodsDetail, createApproval, getSectionList, loadSecGoodsList} from "@/api/ecw/boxSea";
import {getAbnormalList, getbox, getLogList} from "@/api/ecw/box";
import {getTotlContent} from "@/views/ecw/box/shippingSea/utils";
import WorkFlow from "@/components/WorkFlow";
import Template from "@/views/cms/template/index.vue";

export default {
  name: "batchMarkup",
  components: {Template, selector, WorkFlow},
  data(){
    return {
      unitList:[],
      currencyList:[],
      form:{
        copyUserId:[],
        freightUnitId: 6,
        clearanceUnitId: 6
      },
      // 表格多选
      multipleSelection: [],
      // 选择的id
      ids: [],
      channelList:[],
      cabinetList:[],
      sectionList:[],
      // warehouseList:[],
      // allSupplier:[]
      shipmentObj: null,
      shipmentId: null,
      // 当前选择的部分
      sectionId: 0,
      sectionObj: null
    }
  },
  computed:{
    currencyMap(){
      let map = {}
      this.currencyList.forEach(item => {
        map[item.id] = this.$l(item, 'title')
      })
      return map
    },
    unitMap(){
      let map = {}
      this.unitList.forEach(item => {
        map[item.id] = this.$l(item, 'title')
      })
      return map
    },
    /* 渠道 */
    getShipChannelName() {
      return (shippingChannelId) => {
        let item = this.channelList.find(item => item.channelId == shippingChannelId)
        if(!item) return ''
        return this.$l(item, "name");
      };
    },
    /* 获取柜型 */
    getCabinetLabel() {
      return (cabinetId) => {
        return this.cabinetList.find(item => item.id == cabinetId)?.name
      };
    },
    /* 总计 */
    getBoxSum() {
      return (boxStatistics) => {
        if (boxStatistics) {
          return this.$t("{num}箱 {volume}m³ {weight}kg", {
            num: boxStatistics.num ?? 0,
            volume: boxStatistics.volume ?? 0,
            weight: boxStatistics.weight ?? 0,
          });
        }
        return 0;
      };
    },
    /* 获取仓库 */
    getCityName() {
      return (id) => {
        if(!this.warehouseList || !this.warehouseList.length) return ''
        let warehouse = this.warehouseList.find((item) => item.id == id);
        return warehouse ? this.$l(warehouse, "title") : this.$t("无");
      };
    },
    // 部分信息
    getSectionInfo() {
      const { totalStatistics, secStatistics } = this.sectionObj;
      if (!this.sectionId) {
        return getTotlContent(totalStatistics);
      } else {
        return getTotlContent(secStatistics);
      }
    },
    getDocStatus() {
      return (list = []) => {
        // 获取类型
        let customsTypes = list.map((item) => item.customsType);
        // 去重
        return Array.from(new Set(customsTypes));
      };
    },
    // 是否审核中
    approval(){
      return this.shipmentObj?.batchAddPriceApprovalInfo?.approvalStatus === 1
    }
  },
  async created() {
    getUnitList().then(res => this.unitList = res.data)
    getCurrencyList().then(res => this.currencyList = res.data)
    this.shipmentId = this.$route.query.shipmentId
    if(!this.shipmentId){
      return this.$message.error('请求参数错误')
    }
    await this.getBoxDetail()
    await this.initData()
    await this.getSectionList()

    // 如果是审核中，则默认选中订单
    this.$nextTick(() =>{
      if(this.approval){
        this.sectionObj.sectionOrderList.forEach(order => {
          if(this.form.orderIds.indexOf(order.orderId) > -1){
            this.$refs.orderTable.toggleRowSelection(order)
          }
        })
      }
    })

  },
  methods:{
    // 检查正数
    checkPositive(object, field){
      object[field] = parseFloat(object[field])
      object[field] = isNaN(object[field]) ? '' : object[field].toString()
    },
    // 表格多选
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.ids = selection.map(item => item.orderId)
    },
    // 初始化字典数据
    async initData() {
      // 查询渠道
      getChannelList().then((res) => (this.channelList = res.data));
      // 查询柜型
      getCabinetPage(null).then(
        (response) => (this.cabinetList = response.data.list)
      );
      // 仓库
      getWarehouseList().then((r) => {
        this.warehouseList = r.data;
      });
      /*// 供应商
      getSupplierPage({ pageNo: "1", pageSize: "10000" }).then((res) => {
        const { data } = res;
        this.allSupplier = data.list;
      });*/
      /*loadSecGoodsList({shipmentId: this.shipmentId}).then(res => {
        this.sectionList = res.data
      })*/
      await this.getBoxGoodsDetail()
    },
    // 出货信息
    getBoxDetail() {
      getbox(this.shipmentId).then((res) => {
        const { data } = res;
        this.shipmentObj = data ?? {};
        // 如果是审核中则表单给默认值
        if(this.shipmentObj.batchAddPriceApprovalInfo && this.approval){
          let details = JSON.parse(this.shipmentObj.batchAddPriceApprovalInfo.details)
          this.$set(this, 'form', details)
        }
      });
    },
    // 查询详情页所有数据
    getSectionList() {
      let param = { shipmentId: this.shipmentId };
      // 部分
      return getSectionList(param).then((res) => {
        this.sectionList = res.data.map((item, index) => {
          return {
            ...item,
            title: this.$t("第{index}部分", { index: index + 1 }),
          };
        });
      });
    },
    /* 跳转订单详情 */
    jumpOrderDetail(row) {
      this.$router.push({
        path: "/order/detail",
        query: { orderId: row.orderId },
      });
    },
    // 部分切换
    sectionChange() {
      this.getBoxGoodsDetail();
    },
    // 获取部分详情以及物品
    getBoxGoodsDetail() {
      return boxGoodsDetail({
        shipmentId: this.shipmentId,
        secId: this.sectionId,
      }).then((res) => {
        this.sectionObj = res.data;
      });
    },
    // 提交审核
    submit(){
      if(!this.form.freightFee && !this.form.clearanceFee){
        return this.$message.error(this.$t('运费和清关费不能同时为空'))
      }
      if(!this.ids.length){
        return this.$message.error(this.$t('最少选择一个订单'))
      }
      let form = {...this.form, orderIds: this.ids}
      let data = {
        approvalType: 18, // 批量加价
        copyUserId: this.form.copyUserId,
        details: JSON.stringify(form),
        shipmentId: this.shipmentId
      }
      createApproval(data).then(() => {
        this.$message.success(this.$t('提交成功'))
        this.$store.dispatch('tagsView/delCurrentView')
      })
    },
    // 取消审核
    cancelAproval(){
      this.$prompt(this.$t('请输入取消原因'), this.$t('取消审核'), {
        inputPattern: /\S/,
        inputErrorMessage: this.$t('请输入取消原因')
      }).then(({value}) => {
        console.log('cancelApproval', value)
        return approvalCancel({
          applyReason: value,
          id: this.shipmentObj.batchAddPriceApprovalInfo.id,
          shipmentId: this.shipmentId
        })
      }).then(res => {
        this.$message.success('已取消审核')
        this.getBoxDetail()
      })
    }
  }
}
</script>

<style scoped>
.document-status .document ~ .document:before{
  content: '，';
}
</style>
