<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item :label="$t('编号')">
        <el-input
          v-model.trim="noParam.value"
          :placeholder="$t('请输入快递号、包裹号、订单号')"
          clearable
          class="w-200"
          @input="replaceSpace(noParam, 'value')"
          @keyup.enter.native="handleQuery">
          <template slot="prepend">
            <dict-selector :type="DICT_TYPE.ORDER_QUERY_NO_FIELD" defaultable v-model="noParam.key" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="发货人" prop="customerNumber">
        <el-input v-model="queryParams.customerKey" placeholder="请输入发货人手机号、客户编号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="发货人名称" prop="customerNumber">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item :label="$t('集运仓')">
        <el-select v-model="queryParams.wareId" :placeholder="$t('请选择仓库')" filterable>
          <el-option v-for="warehouse in this.warehouseList" :key="warehouse.id" :label="$l(warehouse,'title')" :value="warehouse.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('客户经理')">
        <user-selector manage v-model="queryParams.salesmanIds" multiple clearable @change="handleQuery" :prepend="{ id: 0, nickname: $t('未分配客户经理') }" class="w-200" />
      </el-form-item>
      <el-form-item :label="$t('运输方式')" prop="transportId">
        <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="queryParams.transportId" class="w-200" />
      </el-form-item>
      <el-form-item :label="$t('目的国')" prop="consigneeCountryId">
        <el-select v-model="queryParams.consigneeCountryId"  :label="queryParams.consigneeCountryId" :placeholder="$t('请选择目的国')" clearable @change="handleQuery" class="w-200">
          <el-option v-for="item in AddressProvince" :key="item.guojia" :label="item.guojiaName" :value="item.guojia"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('目的城市')" prop="objectiveId">
        <el-select v-model="queryParams.consigneeCityId"  :placeholder="$t('请选择目的城市')" style="width: 200px" clearable @change="handleQuery" class="w-200">
          <el-option v-for="item in AddressCity" :key="item.shi" :label="item.shiName" :value="item.shi"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('出货渠道')" prop="shippingChannelIdList">
        <el-select v-model="queryParams.shippingChannelIdList" multiple :placeholder="$t('请选择出货渠道')" clearable>
          <el-option v-for="item in channelList" :label="$l(item, 'name')" :value="item.channelId" :key="item.channelId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['ecw:cons:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['ecw:cons:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="快递单号" align="center" prop="expressNo" />
      <el-table-column label="客户" align="center">
        <template slot-scope="scope">
          {{scope.row.customerName}}({{scope.row.customerNumber}})
        </template>
      </el-table-column>>
      <el-table-column :label="$t('运输方式')" align="center" >
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="scope.row.transportId" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('动态')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.CONS_BUSINESS_NODE" :value="scope.row.businessNode" />
        </template>
      </el-table-column>
      <el-table-column label="最新跟进时间" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.trackingTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="箱数" align="center" prop="sumQuantity" />
      <el-table-column label="填单商品" align="center">
        <template slot-scope="scope">
          <span v-html="getGoodsName(scope.row.consItemList)"></span>
        </template>
      </el-table-column>
      <el-table-column label="验货数据" align="center">
        <template slot-scope="scope">
          {{getInspectionInfo(scope.row.consItemList)}}
        </template>
      </el-table-column>
      <el-table-column label="货值(RMB)" align="center" prop="worth" />
<!--      <el-table-column label="预计到仓时间" align="center" prop="watEtime" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.watEtime) }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="签收时间" align="center" prop="signedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signedTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签收备注" align="center" prop="signedRemarks" />
      <el-table-column label="始发仓" align="center">
        <template slot-scope="scope">
          {{isChinese?scope.row.startTitleZh:scope.row.startTitleEn}}
        </template>
      </el-table-column>
      <el-table-column label="目的仓" align="center">
        <template slot-scope="scope">
          {{isChinese?scope.row.destTitleZh:scope.row.destTitleEn}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('出货渠道')" align="center">
        <template slot-scope="scope">
          {{scope.row.channelName||"/"}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('验货')" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.needInspect==='0'">
            {{$t('未申请')}}
          </template>
          <template v-else>
              <dict-tag :type="DICT_TYPE.CONS_INSPECT_STATUS" :value="scope.row.inspectStatus" />
          </template>
        </template>
      </el-table-column>
      <el-table-column :label="$t('包裹状态')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.CONS_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="关联订单号" align="center" prop="orderNo" />
      <el-table-column :label="$t('订单状态')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="scope.row.orderStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('退仓处理状态')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.AUDIT_STATUS" :value="scope.row.returnStatus" />
        </template>
      </el-table-column>
      <el-table-column label="包裹号" align="center" prop="consNum" />
      <el-table-column label="包裹备注" align="center" prop="remarks" />
      <el-table-column label="" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['ecw:cons:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['ecw:cons:delete']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="transmutation(scope.row)">{{$t('转异')}}</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="specialNeedsCons(scope.row)">{{$t('特需')}}</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="specialNeedsConsLook(scope.row)">{{$t('特需查看')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="客户编号" prop="customerNumber">
          <el-input v-model="form.customerNumber" placeholder="请输入客户编号" />
        </el-form-item>
        <el-form-item label="运输方式，来自字典的值" prop="transportId">
          <el-input v-model="form.transportId" placeholder="请输入运输方式，来自字典的值" />
        </el-form-item>
        <el-form-item label="订单ID，关联订单表" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单ID，关联订单表" />
        </el-form-item>
        <el-form-item label="平台ID，关联平台表数据，为后面系统对接预留字段" prop="platformId">
          <el-input v-model="form.platformId" placeholder="请输入平台ID，关联平台表数据，为后面系统对接预留字段" />
        </el-form-item>
        <el-form-item label="平台订单号" prop="platformOrderSn">
          <el-input v-model="form.platformOrderSn" placeholder="请输入平台订单号" />
        </el-form-item>
        <el-form-item label="包裹状态，来自字典表，cons_status" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="快递公司ID，对应快递公司表" prop="expressId">
          <el-input v-model="form.expressId" placeholder="请输入快递公司ID，对应快递公司表" />
        </el-form-item>
        <el-form-item label="快递单号" prop="expressNo">
          <el-input v-model="form.expressNo" placeholder="请输入快递单号" />
        </el-form-item>
        <el-form-item label="仓库ID" prop="wareId">
          <el-input v-model="form.wareId" placeholder="请输入仓库ID" />
        </el-form-item>
        <el-form-item label="货值" prop="worth">
          <el-input v-model="form.worth" placeholder="请输入货值" />
        </el-form-item>
        <el-form-item label="货值单位，默认为3，人民币" prop="worthCurrency">
          <el-input v-model="form.worthCurrency" placeholder="请输入货值单位，默认为3，人民币" />
        </el-form-item>
        <el-form-item label="预计到仓时间" prop="watEtime">
          <el-date-picker clearable v-model="form.watEtime" type="date" value-format="yyyy-MM-dd" placeholder="选择预计到仓时间" />
        </el-form-item>
        <el-form-item label="" prop="watTime">
          <el-date-picker clearable v-model="form.watTime" type="date" value-format="yyyy-MM-dd" placeholder="选择" />
        </el-form-item>
        <el-form-item label="是否被签收,0未签收，1已签收" prop="signed">
          <el-radio-group v-model="form.signed">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="签收时间" prop="signedTime">
          <el-date-picker clearable v-model="form.signedTime" type="date" value-format="yyyy-MM-dd" placeholder="选择签收时间" />
        </el-form-item>
        <el-form-item label="签收备注" prop="signedRemarks">
          <el-input v-model="form.signedRemarks" placeholder="请输入签收备注" />
        </el-form-item>
        <el-form-item label="数量" prop="sumQuantity">
          <el-input v-model="form.sumQuantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="区分包裹是由谁创建的，关联字典表 cons_op_source，可区分为后台创建、客户web端、客户app端、客户H5端、仓库创建及其他，默认为1 客户app端" prop="opSource">
          <el-input v-model="form.opSource" placeholder="请输入区分包裹是由谁创建的，关联字典表 cons_op_source，可区分为后台创建、客户web端、客户app端、客户H5端、仓库创建及其他，默认为1 客户app端" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <Transmutation :showException.sync="showException" :id="id" @determine="getList"></Transmutation>
    <SpecialNeedsCons :showSpecialNeedsCons.sync="showSpecialNeedsCons" :currency="JSON.stringify(currencyList)" :consId="id" :consNum="consNum" @determine="getList"></SpecialNeedsCons>
    <SpecialNeedsConsLook :showSpecialNeedsConsLook.sync="showSpecialNeedsConsLook" :consNum="consNum" :consId="id"></SpecialNeedsConsLook>

  </div>
</template>

<script>
import {createCons, deleteCons, exportConsExcel, getCons, getConsPage, updateCons} from "@/api/ecw/cons";
import Transmutation from "@/views/ecw/cons/components/Transmutation.vue"
import Template from "@/views/cms/template/index.vue";
import UserSelector from "@/components/UserSelector/index.vue";
import { getWarehouseList } from "@/api/ecw/warehouse";
import {getTradeCountryList} from "@/api/ecw/region";
import {getRegionList} from "@/api/ecw/order";
import SpecialNeedsCons from "@/views/ecw/cons/components/SpecialNeedsCons.vue"
import SpecialNeedsConsLook from "@/views/ecw/cons/components/SpecialNeedsConsLook.vue"

import { getCurrencyList } from "@/api/ecw/currency"

export default {
  name: "Cons",
  components: {
    UserSelector,
    Transmutation,
    Template,
    SpecialNeedsConsLook,
    SpecialNeedsCons
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 集运包裹主列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 编号搜索条件
      noParam: {
        key: "numberKey",
        value: ""
      },
      dateRangeWatEtime: [],
      warehouseList:[],
      AddressProvince:[],
      AddressCity:[],
      dateRangeWatTime: [],
      dateRangeSignedTime: [],
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        customerId: null,
        customerNumber: null,
        transportId: null,
        orderId: null,
        platformId: null,
        platformOrderSn: null,
        status: null,
        expressId: null,
        expressNo: null,
        wareId: null,
        worth: null,
        worthCurrency: null,
        signed: null,
        signedRemarks: null,
        sumQuantity: null,
        opSource: null,
        remarks: null,
      },
      // 表单参数
      form: {
        transportId: null,
      },
      // 表单校验
      rules: {
        signed: [{ required: true, message: "是否被签收,0未签收，1已签收不能为空", trigger: "blur" }],
      },
      showException: false,
      showSpecialNeedsCons: false,
      showSpecialNeedsConsLook: false,
      id: null,
      currencyList: [],
      consNum: null,
    };
  },
  created() {
    this.getList();
    getWarehouseList().then((r) => {
      this.warehouseList = r.data;
    });
    this.getAddressProvince()
    this.getAddressCity()
    getCurrencyList().then((res) => (this.currencyList = res.data))
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === "zh_CN";
    },
    combinedQueryParams(){
      console.log(this.queryParams)
      let queryParams = {...this.queryParams}
      if (this.noParam.value) {
        queryParams[this.noParam.key] = this.noParam.value
      }
      return queryParams
    },
  },
  watch: {
    'queryParams.consigneeCountryId': {
      deep: true, //深度监听
      handler() {
        if (this.queryParams.consigneeCountryId != "") {
          this.findByprovinceCode()
        }
      }
    },
  },
  methods: {
    getAddressProvince() {
      getRegionList(1, 1).then(({ data }) => {
        this.AddressProvince = data
      })
    },
    getAddressCity() {
      getRegionList(4, 4).then(({ data }) => {
        this.AddressCity = data
      })
    },
    findByprovinceCode() {
      if (this.queryParams.consigneeCountryId != null && this.queryParams.consigneeCountryId != "") {
        //获取当前省份值id，获取该省份下城市 destCountryId provinceCode
        getRegionList(2, this.queryParams.consigneeCountryId).then(({ data }) => {
          this.AddressCity = data
        })
      }
    },
    // 自动去除空格
    replaceSpace(obj, field) {
      obj[field] = obj[field].replace(/\s+/g, "")
    },
    getGoodsName(val){
      return val.map((item, index) => `${index + 1}.${item.prodName}*${item.quantity}`).join('<br>');
    },
    getInspectionInfo(val){
      let inspectionNums = 0;
      let inspectionUnit;
      let inspectionQuantitys=0;
      let inspectionVolumes=0;
      let inspectionWeights=0;
      val.forEach(item => {
        inspectionUnit = item.inspectionUnit;
        inspectionNums += item.inspectionNum;
        inspectionQuantitys += item.inspectionQuantity;
        inspectionVolumes += item.inspectionVolume;
        inspectionWeights += item.inspectionWeight;
      });
      return `${inspectionQuantitys}${inspectionUnit} ${inspectionVolumes}m³ ${inspectionWeights}kg ${inspectionNums}件`;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = { ...this.combinedQueryParams };
      console.log(params)
      this.addBeginAndEndTime(params, this.dateRangeWatEtime, 'watEtime');
      this.addBeginAndEndTime(params, this.dateRangeWatTime, 'watTime');
      this.addBeginAndEndTime(params, this.dateRangeSignedTime, 'signedTime');
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getConsPage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        customerId: undefined,
        customerNumber: undefined,
        transportId: undefined,
        orderId: undefined,
        platformId: undefined,
        platformOrderSn: undefined,
        status: undefined,
        expressId: undefined,
        expressNo: undefined,
        wareId: undefined,
        worth: undefined,
        worthCurrency: undefined,
        watEtime: undefined,
        watTime: undefined,
        signed: undefined,
        signedTime: undefined,
        signedRemarks: undefined,
        sumQuantity: undefined,
        opSource: undefined,
        remarks: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeWatEtime = [];
      this.dateRangeWatTime = [];
      this.dateRangeSignedTime = [];
      this.dateRangeCreateTime = [];
      this.noParam.value = ""
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加集运包裹主";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getCons(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改集运包裹主";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateCons(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createCons(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除集运包裹主编号为"' + id + '"的数据项?').then(function() {
          return deleteCons(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeWatEtime, 'watEtime');
      this.addBeginAndEndTime(params, this.dateRangeWatTime, 'watTime');
      this.addBeginAndEndTime(params, this.dateRangeSignedTime, 'signedTime');
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有集运包裹主数据项?').then(() => {
          this.exportLoading = true;
          return exportConsExcel(params);
        }).then(response => {
          this.$download.excel(response, '${table.classComment}.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
    //转异
    transmutation(row) {
      this.id = row.id
      this.showException = true
    },
    //特需
    specialNeedsCons(row) {
      this.id = row.id
      this.consNum = row.consNum
      this.showSpecialNeedsCons = true
    },
    //特需查看
    specialNeedsConsLook(row) {
      this.id = row.id
      this.consNum = row.consNum
      this.showSpecialNeedsConsLook = true
    }
  }
};
</script>
