<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addOrEditDialogFlag"
    :title="title"
    :append-to-body="false"
    :close-on-click-modal="false"
    :maxable="true"
    :resizable="true"
    width="50%"
    :before-close="cancel"
  >
    <el-form ref="form" :rules="rules" :model="form" label-width="120px">
      <headerTitle title="基础信息"></headerTitle>
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务类型" prop="taskType">
            <DictSelection
              clearable
              dictName="派车任务类型"
              v-model="form.taskType"
              :disabled="dialogType === 'view'"
              @itemChange="(val) => handleChangeFinLink(val)"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-row>
            <el-col :span="20">
              <el-form-item label="车牌号" prop="trakNumber">
                <el-input v-model="form.trakNumber"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="display: flex; justify-content: flex-end">
              <el-button type="primary" @click="handleCar">选择</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-row>
            <el-col :span="20">
              <el-form-item label="司机" prop="driverName">
                <el-input v-model="form.driverName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="display: flex; justify-content: flex-end">
              <el-button type="primary" @click="handleDriver">选择</el-button>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12">
          <el-form-item label="里程" prop="mileage">
            <el-input type="number" :min="0" v-model="form.mileage" clearable>
              <template slot="append">KM</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="电话" prop="mileage">
            <el-input v-model="form.phone" clearable> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计费方式" prop="billingMethod">
            <el-select
              v-model="form.billingMethod"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in billingMethodList"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="数量" prop="quantity">
            <el-input
              type="number"
              :controls="false"
              style="width: 100%"
              :min="0"
              v-model="form.quantity"
              @change="handleGetTotalCost"
            >
              <template v-if="form.billingMethod == 1" slot="append"
                >m³</template
              >
              <template v-else-if="form.billingMethod == 2" slot="append"
                >KG</template
              >
              <template v-else slot="append">辆车</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单价" prop="price">
            <el-input-number
              :controls="false"
              style="width: 100%"
              :min="0"
              v-model="form.price"
              @change="handleGetTotalCost"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="出发地" prop="startPlace">
            <el-input v-model="form.startPlace"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目的地" prop="endPlace">
            <el-input v-model="form.endPlace"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="开始时间" prop="realStartTime">
            <el-date-picker
              v-model="form.realStartTime"
              :picker-options="{
                disabledDate: (time) => {
                  return (
                    form.realEndTime &&
                    time.getTime() > new Date(form.realEndTime)
                  );
                }
              }"
              type="datetime"
              style="width: 100%"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="完成时间" prop="realEndTime">
            <el-date-picker
              v-model="form.realEndTime"
              :picker-options="{
                disabledDate: (time) => {
                  return (
                    form.realStartTime &&
                    time.getTime() < new Date(form.realStartTime)
                  );
                }
              }"
              type="datetime"
              style="width: 100%"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="总费用" prop="totalCost">
            <el-input v-model="form.totalCost" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="单据来源" required>
            <!-- <el-input
              v-model="form.taskCode"
              @click.native="(val) => handleSelectData(val)"
              clearable
            ></el-input> -->
            <el-button type="primary" @click="handleSelectData">选择</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <ele-pro-table
          ref="table"
          :columns="documentList"
          :datasource="tableList"
          row-key="id"
          class="dict-table"
        >
        </ele-pro-table>
      </el-row>
    </el-form>

    <div slot="footer">
      <el-button type="primary" @click="handleSave" v-if="dialogType != 'view'"
        >保存</el-button
      >
      <el-button @click="cancel">返回</el-button>
    </div>
    <!-- 选择司机   -->
    <select-driver-dialog
      ref="selectDriverDialogRef"
      :selectDriverDialogFlag.sync="selectDriverDialogFlag"
      v-if="selectDriverDialogFlag"
      @changeParent="getDriverInfo"
    ></select-driver-dialog>
    <select-car-dialog
      ref="selectCarDialogRef"
      :selectCarDialogFlag.sync="selectCarDialogFlag"
      v-if="selectCarDialogFlag"
      @changeParent="getCarInfo"
    ></select-car-dialog>
    <!--  销售发货单  -->
    <sendListDialog
      v-if="sendListDialogVisible"
      :sendListDialogVisible.sync="sendListDialogVisible"
      ref="sendListDialogRef"
      @changeParent="changeOrder"
    ></sendListDialog>
    <!-- 委外发货单   -->
    <out-source-send-dialog
      :out-source-send-dialog-flag.sync="outSourceSendDialogFlag"
      v-if="outSourceSendDialogFlag"
      ref="outSourceSendDialogRef"
      @changeParent="getOutSourceInfo"
    ></out-source-send-dialog>
    <!--  采购收货单  -->
    <purchaseReceivingGoodsDialog
      ref="purchaseReceivingGoodsRef"
      @changeParent="getPurchaseReceivingGoodsInfo"
    ></purchaseReceivingGoodsDialog>
    <!--  受托发货单  -->
    <entrusted-receive-dialog
      :entrusted-receive-dialog-flag.sync="entrustedReceiveDialogFlag"
      v-if="entrustedReceiveDialogFlag"
      @changeParent="getEntrustedReceiveInfo"
      ref="entrustedReceiveDialogRef"
    ></entrusted-receive-dialog>
    <!-- 销售退货   -->
    <return-order-dialog
      :returnOrderDialogFlag.sync="returnOrderDialogFlag"
      v-if="returnOrderDialogFlag"
      @changeParent="getSReturnOrderInfo"
      ref="returnOrderDialogRef"
    >
    </return-order-dialog>
    <!-- 采购退货   -->
    <purchase-return-order-dialog
      :purchaseReturnOrderDialogFlag.sync="purchaseReturnOrderDialogFlag"
      v-if="purchaseReturnOrderDialogFlag"
      @changeParent="getPReturnOrderInfo"
      ref="returnOrderDialogRef"
    ></purchase-return-order-dialog>

    <!-- 调拨发货   -->
    <inventory-allocation-dialog
      ref="inventoryAllocationDialogRef"
      :inventoryAllocationDialogFlag.sync="inventoryAllocationDialogFlag"
      v-if="inventoryAllocationDialogFlag"
      @changeParent="getTransferSendInfo"
    ></inventory-allocation-dialog>

  </ele-modal>
</template>

<script>
  import { logistictraklistnoteSaveAPI } from '@/api/transportManager/shipManage/taskWork';
  import selectCarDialog from '@/views/transportManager/shipManage/dispatchManage/components/selectCarDialog.vue';
  import selectDriverDialog from '@/views/transportManager/shipManage/dispatchManage/components/selectDriverDialog.vue';
  import returnOrderDialog from '@/views/saleManage/saleOrder/customerReturnOrder/returnOrderDialog.vue';
  import entrustedReceiveDialog from '@/views/saleManage/saleOrder/invoice/components/entrustedReceiveDialog.vue';
  import outSourceSendDialog from '@/views/purchasingManage/purchaseOrder/invoice/components/outSourceSendDialog.vue';
  import sendListDialog from '@/views/transportManager/shipManage/taskWorkManage/components/sendListDialog.vue';
  import purchaseReceivingGoodsDialog from '@/views/purchasingManage/purchaseOrder/returnGoods/components/sendListDialog.vue';
  import purchaseReturnOrderDialog from '@/views/transportManager/shipManage/dispatchManage/components/purchaseReturnOrderDialog.vue';
  import inventoryAllocationDialog from '@/views/transportManager/shipManage/dispatchManage/components/inventoryAllocationDialog.vue';

  export default {
    name: 'addOrEditDialog',
    components: {
      selectCarDialog,
      selectDriverDialog,
      returnOrderDialog,
      entrustedReceiveDialog,
      outSourceSendDialog,
      sendListDialog,
      purchaseReceivingGoodsDialog,
      purchaseReturnOrderDialog,
      inventoryAllocationDialog
    },

    props: {
      addOrEditDialogFlag: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        editIndex: undefined, //当前修改数据的下标
        selectCarDialogFlag: false,
        selectDriverDialogFlag: false,
        outSourceSendDialogFlag: false,
        entrustedReceiveDialogFlag: false,
        returnOrderDialogFlag: false,
        purchaseReturnOrderDialogFlag: false,
        inventoryAllocationDialogFlag: false,
        billingMethodList: [
          {
            label: '按方计费',
            value: 1
          },
          {
            label: '按重量计费',
            value: 2
          },
          {
            label: '专车计费',
            value: 3
          }
        ],
        title: '',
        form: {
          // id: '',
          trakId: '',
          trakNumber: '',
          driverId: '',
          driverName: '',
          phone: '',
          taskType: '',
          // taskCode: '',
          realStartTime: '',
          realEndTime: '',
          startPlace: '',
          endPlace: '',
          billingMethod: 1,
          totalCost: '',
          price: undefined,
          quantity: '',
          remark: '',
          type: 1
        },
        dialogType: '',
        rules: {
          taskType: { required: true, message: '请选择', trigger: 'change' },
          // taskCode: { required: true, message: '请选择', trigger: 'change' },
          trakNumber: { required: true, message: '请选择', trigger: 'change' },
          billingMethod: {
            required: true,
            message: '请选择',
            trigger: 'change'
          },
          price: {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur']
          },
          quantity: {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur']
          },
          driverName: { required: true, message: '请选择', trigger: 'change' }
        },
        currentRow: {},
        sendListDialogVisible: false,
        tableList: [],
        documentList: [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'code',
            label: '单据编码',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'orderNo',
            label: '订单编码',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'contactName',
            label: '名称',
            align: 'center',
            showOverflowTooltip: true
          }
        ]
      };
    },
    mounted() {},
    methods: {
      //初始化
      async init(row = {}, type) {
        this.currentRow = row;
        this.dialogType = type;
        this.title = type == 'add' ? '新增' : '修改';
        this.form.id = this.currentRow.id;
      },
      handleGetTotalCost(val) {
        if (this.form.quantity && this.form.price) {
          this.form.totalCost =
            Number(this.form.quantity) * Number(this.form.price);
        } else {
          this.form.totalCost = '';
        }
      },
      //选择司机
      handleDriver(row, index) {
        this.selectDriverDialogFlag = true;
      },
      //选择司机回调
      getDriverInfo(row) {
        this.form.driverId = row.driverId;
        this.form.driverName = row.driverName;
        this.form.phone = row.phone;
      },
      //选择车辆
      handleCar(row, index) {
        this.selectCarDialogFlag = true;
      },
      //选择车辆回调
      getCarInfo(row) {
        this.form.driverId = row.defaultDriverId;
        this.form.driverName = row.defaultDriver;
        this.form.phone = row.phone;
        this.form.trakNumber = row.trakNumber;
        this.form.trakId = row.id;
      },
      cancel() {
        this.$emit('update:addOrEditDialogFlag', false);
      },
      //修改任务类型
      handleChangeFinLink(val, row, index) {
        // this.setSelectData({
        //   id: '',
        //   code: ''
        // });
        this.tableList = [];
      },
      setSelectData(val) {
        // this.$set(this.form, 'taskId', val.id);
        // this.$set(this.form, 'taskCode', val.code);
        console.log(val, 'val ++++++++++');
      },
      handleSelectData(val, row, index) {
        // if (val.target.nodeName == 'I') {
        //   this.form.taskId = '';
        //   this.form.taskCode = '';
        //   return;
        // }
        if (!this.form.taskType) {
          this.$message.warning('请先选择任务类型');
          return;
        }
        switch (this.form.taskType) {
          case '1': //销售发货
            this.handleOrderBtn(row);
            break;
          case '2': //委外发货
            this.handleOutsourceSend(row);
            break;
          case '3': //采购收货
            this.handlePurchaseReceivingGoods(row);
            break;
          case '4': //受托发货
            this.handleEntrustedReceive(row);
            break;
          case '5': //销售退货
            this.handleSaleReturnOrder(row);
            break;
          case '6': //采购退货
            this.handlePurchaseReturnOrder(row);
            break;
          case '7': //调拨发货
            this.handleTransferSend(row);
            break;
        }
      },
      //选择调拨发货单
      handleTransferSend() {
        this.inventoryAllocationDialogFlag = true;
      },
      //调拨发货单回调
      getTransferSendInfo(params) {
        console.log(params, 'params ++++++++++');
        let row = {
          id: params.id,
          code: params.allotCode,
          orderNo: params.saleOrderNos,
          contactName: params.name
        };
        this.tableList = [row];
        // this.tableList = params.map((item) => {
        //   return {
        //     id: item.id, // id
        //     code: item.allotCode, // 发货编码
        //     orderNo: item.saleOrderNos,
        //     contactName: item.name
        //   };
        // });
      },
      //选择发货单
      handleOrderBtn() {
        // this.$refs.sendListDialogRef.open();
        this.sendListDialogVisible = true;
      },
      //选择发货单回调 ****
      changeOrder(params) {
        // let row = {
        //   id: params.id,
        //   code: params.docNo
        // }
        // this.setSelectData(row)
        // this.setSelectData(params);
        this.tableList = params.map((item) => {
          return {
            id: item.id, // id
            code: item.docNo, // 发货编码
            orderNo: item.orderNo,
            contactName: item.contactName
          };
        });
      },
      //选择采购收货单
      handlePurchaseReceivingGoods() {
        this.$refs.purchaseReceivingGoodsRef.open();
      },
      //选择采购收货单回调 ****
      getPurchaseReceivingGoodsInfo(params) {
        // let row = {
        //   id: params.id,
        //   code: params.receiveNo
        // };
        // this.setSelectData(row);
        let row = {
          id: params.id,
          code: params.receiveNo,
          orderNo: params.orderNo,
          contactName: params.supplierName
        };
        this.tableList = [row];
      },

      //选择委外发货单弹框
      handleOutsourceSend() {
        this.outSourceSendDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.outSourceSendDialogRef.init();
        });
      },
      //选择委外发货单回调
      getOutSourceInfo(params) {
        // let row = {
        //   id: params.id,
        //   code: params.code
        // };
        // this.setSelectData(row);
        let row = {
          id: params.id,
          code: params.code,
          orderNo: params.orderNo,
          contactName: params.supplierName
        };
        this.tableList = [row];
      },
      //选择受托收货单弹框
      handleEntrustedReceive(e) {
        this.entrustedReceiveDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.entrustedReceiveDialogRef.init();
        });
      },
      //获取受托收货单数据回调
      async getEntrustedReceiveInfo(params) {
        // let row = {
        //   id: params.id,
        //   code: params.code
        // };
        // this.setSelectData(row);
        let row = {
          id: params.id,
          code: params.code,
          orderNo: params.orderNo,
          contactName: params.contactName
        };
        this.tableList = [row];
      },
      //选择销售退货单
      handleSaleReturnOrder() {
        this.returnOrderDialogFlag = true;
        // this.$nextTick(() => {
        //   this.$refs.returnOrderDialogRef.init()
        // })
      },
      //销售退货单回调
      getSReturnOrderInfo(params) {
        // let row = {
        //   id: params.id,
        //   code: params.returnNo
        // };
        // this.setSelectData(row);
        let row = {
          id: params.id,
          code: params.returnNo,
          orderNo: params.orderNo,
          contactName: params.contactName
        };
        this.tableList = [row];
      },
      //选择采购退货单
      handlePurchaseReturnOrder() {
        this.purchaseReturnOrderDialogFlag = true;
      },
      //采购退货单回调
      getPReturnOrderInfo(params) {
        // let row = {
        //   id: params.id,
        //   code: params.returnNo
        // };
        // this.setSelectData(row);

        let row = {
          id: params.id,
          code: params.returnNo,
          orderNo: params.orderNo,
          contactName: params.contactName
        };
        this.tableList = [row];
      },
      //
      handleSave() {
        if (this.tableList.length == 0) {
          return this.$message.warning('请选择单据来源数据');
        }
        this.$refs.form.validate(async (valid) => {
          if (!valid) return this.$message.warning('有必填项未填，请检查');
          let params = {
            ...this.form
          };
          // ***** 新增需求 销售发货可以选择多个 其它的还是一个
          if (this.form.taskType == 1) {
            params.orderSendIds = this.tableList.map((item) => item.id);
          } else {
            params.taskCode = this.tableList[0].code;
            params.taskId = this.tableList[0].id;
          }
          await logistictraklistnoteSaveAPI(params);
          this.$message.success('操作成功');
          this.$emit('reload');
          this.cancel();
        });
      }
    }
  };
</script>

<style scoped lang="scss">
  :deep(.el-form-item) {
    margin-bottom: 20px;
  }
</style>
