<template>
  <div>
    <el-dialog
      title="订单发货"
      :visible.sync="sendShow"
      width="800px"
      :before-close="close"
    >
      <el-form
        :model="shipForm"
        ref="shipForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="订单号：">
          <span>{{ goodsInfo.orderId }}</span>
        </el-form-item>
        <el-form-item label="收货地址：">
          <span>{{
            `${goodsInfo.receiver}，${goodsInfo.tel}，${goodsInfo.province}${goodsInfo.city}${goodsInfo.area}${goodsInfo.address}`
          }}</span>
        </el-form-item>
        <el-form-item label="配送方式：">
          <!--单选框-->
          <el-radio @change="radioDistribution" v-model="shipForm.deliveryType" label="1">快递发货</el-radio>
          <el-radio @change="radioDistribution" v-model="shipForm.deliveryType" label="2">无需物流</el-radio>

        </el-form-item>
        <el-form-item v-if="shipForm.deliveryType == 1" label="快递单号：" prop="deliveryFlowId">
          <el-input
            v-model="shipForm.deliveryFlowId"
            @blur="InputBlur()"
            placeholder="输入快递单号"
            clearable
            size="small"
            style="width: 500px"
          />
        </el-form-item>
        <el-form-item v-if="shipForm.deliveryType == 1"  label="快递公司：" prop="deliveryId">
          <el-select
            v-model="shipForm.deliveryId"
            placeholder="请选择快递公司"
            clearable
            size="small"
            style="width: 500px"
          >
            <el-option
              v-for="item in companyData"
              :key="item.areaId"
              :label="item.companyName"
              :value="item.deliveryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="盲票组：">
          <el-select
            v-model="shipForm.boxId"
            placeholder="请选择盲票组"
            clearable
            size="small"
            style="width: 500px"
          >
            <el-option
              v-for="item in channelList"
              :key="item.areaId"
              :label="item.title"
              :value="item.boxId"
            >
              <div class="channel">
                <div>{{ item.boxNo }}</div>
                <div>{{ item.title }}</div>
                <div>{{ item.orderNum }}包</div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="盲票包序号：">
          <el-autocomplete
            v-model="pkgNo"
            :fetch-suggestions="querySearch"
            placeholder="输入盲票包序号"
            size="small"
            :disabled="shipForm.boxId ? false : true"
            style="width: 500px"
            @select="handleSelect"
          >
            <template slot-scope="{ item }">
              <div class="channel">
                <div>{{ item.startSn }}至{{ item.endSn }}</div>
                <div>{{ item.title }}</div>
              </div>
            </template>
          </el-autocomplete>
        </el-form-item>
      </el-form>
      <!-- 选中盲票组列表 -->
      <div class="table">
        <el-table ref="table" :data="list">
          <el-table-column label="盲票组" prop="title" />
          <el-table-column label="盲票包系列号范围" min-width="100">
            <template slot-scope="{ row }">
              <div>
                <div>{{ row.startSn }}至{{ row.endSn }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="50">
            <template slot-scope="scope">
              <div>
                <el-button
                  type="text"
                  size="small"
                  @click="delList(scope.$index, scope.row)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :disabled="loading" @click="saveClick"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import CustomFieldsMixin from "@/mixins/CustomFields";
import { companyList, ticketPkgList, channelOrderShip, automaticRecognition} from "@/api/business/order";
export default {
  mixins: [CustomFieldsMixin],
  props: {
    // 发货弹框显示
    sendShow: {
      type: Boolean,
      default: false,
    },
    // 订单详情
    goodsInfo: {
      type: Object,
      default: {},
    },
    // 盲票组下拉列表
    channelList: {
      type: Array,
      default: [],
    },
  },
  created() {
    this.getCompanyList();
  },
  data() {
    return {
      loading: false,
      shipForm: {
        deliveryId: "",
        deliveryFlowId: "",
        boxId: "",
        deliveryType:"1",//物流配送方式单选框
      },
      // 快递下拉列表
      companyData: [],
      // 盲票组序列号
      pkgNo: "",
      // 选中盲票组列表
      list: [],
      rules: {
        deliveryId: [
          { required: true, message: "请选择快递公司", trigger: "change" },
        ],
        deliveryFlowId: [
          { required: true, message: "请输入快递单号", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    // 关闭发货弹框
    close() {
      this.$emit("close");
      this.loading = false;
      this.list = [];
      this.shipForm.boxId = "";
      this.$refs["shipForm"].resetFields();
      this.shipForm.deliveryType = "1";
    },

    //切换配送方式时清空另一个方式所选项
    radioDistribution(){
      if(this.shipForm.deliveryType == '2'){
        this.shipForm.deliveryId = '';
        this.shipForm.deliveryFlowId = '';
        this.shipForm.boxId = "";
        this.list = [];
      }
      if(this.shipForm.deliveryType == '1'){
        this.shipForm.boxId = "";
        this.list = [];
      }
    },

    // 快递下拉列表
    getCompanyList() {
      companyList({}).then((res) => {
        this.companyData = res.data;
      });
    },

    //快递单号失去焦点时
    InputBlur(){
      if (this.shipForm.deliveryFlowId){
        automaticRecognition(this.shipForm.deliveryFlowId).then((res)=>{
          if (res.code == 0 && res.data){
            this.shipForm.deliveryId = res.data.deliveryId
          }
        })
      }
    },

    // 查询盲票组序列号
    querySearch(queryString, cb) {
      ticketPkgList({
        orderId: this.goodsInfo.orderId,
        boxId: this.shipForm.boxId,
        pkgNo: this.pkgNo,
      }).then((res) => {
        cb(res.data);
      });
    },

    // 选中盲票组序列号
    handleSelect(item) {
      let index = this.list.findIndex(ele=>{
        return item.pkgId == ele.pkgId
      })
      if(index != -1){
        this.msgError("当前票包已选！");
        return
      }
      this.list.push(item);
    },

    // 删除选中盲票组序列号
    delList(index, row) {
      this.list.splice(index, 1);
    },

    // 确认
    saveClick() {
      this.loading = true;
      const subForm = this.$refs["shipForm"];
      subForm.validate((valid) => {
        if (valid) {
          this.submitForm(this.shipForm);
        } else {
          this.loading = false;
          // 提示第一个error
          this.getFormErrorMessage(subForm);
          return false;
        }
      });
    },

    // 提交
    submitForm(form) {
      let ids = this.list.map((item) => item.pkgId);
      if (!ids.length) {
        this.msgError("请选择发货的票包");
        this.loading = false;
        return;
      }
      if (this.goodsInfo.pkgNum != ids.length) {
        this.msgError(
          `应发${this.goodsInfo.pkgNum}包，实际选中${ids.length}包`
        );
        this.loading = false;
        return;
      }
      let data = {
        ...form,
        orderId: this.goodsInfo.orderId,
        pkgIds: ids,
      };
      channelOrderShip(data)
        .then((res) => {
          if (res.code == 0) {
            this.msgSuccess("发货成功");
            this.close();
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>
<style scoped>
.channel {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
