<template>
  <el-dialog :close-on-click-modal="false" title="物料订单" :append-to-body="appendFlag" :visible.sync="materialDialog" top="20px" width="1000px">
    <el-form :model="form" inline size="mini" :rules="rules" ref="form">
      <template v-if="!seeFlag">
        <template v-if="!editFlag">
          <el-button size="medium" type="green" @click="addMaterialOrder(1)" style="margin-bottom: 10px" :disabled="clickLoading">保存</el-button>
          <el-button size="medium" type="primary" @click="addMaterialOrder(2)" style="margin-bottom: 10px" :disabled="clickLoading">保存并提交</el-button>
        </template>
        <template v-else>
          <el-button size="medium" type="green" @click="addMaterialOrder(3)" style="margin-bottom: 10px" :disabled="clickLoading">修改</el-button>
          <el-button size="medium" type="primary" @click="addMaterialOrder(4)" style="margin-bottom: 10px" :disabled="clickLoading">修改并提交</el-button>
        </template>
      </template>
    <el-card>
        <el-form-item label="客户名称" prop="clientName">
          <el-input v-model="form.clientName" readonly></el-input>
        </el-form-item>
        <el-form-item label="印品名称" prop="orderName">
          <el-input v-model="form.orderName"></el-input>
        </el-form-item>
        <el-form-item label="生产备注">
          <el-input type="textarea" v-model="form.orderMemo"></el-input>
        </el-form-item>
        <el-form-item label="用纸要求">
          <el-checkbox :true-label='1' :false-label="0" v-model="form.paperRequireFlag"></el-checkbox>
        </el-form-item>
        <el-form-item label="包装要求" prop="boxRequire">
          <el-select
            style="width: 100%;"
            collapse-tags
            v-model="form.boxRequire">
            <el-option
              v-for="item in packingMethodOptions"
              :key="item.id"
              :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="打包方式">
          <el-select
            style="width: 100%;"
            collapse-tags
            v-model="form.packKind">
            <el-option
              label="均匀打包"
              :value="0">
            </el-option>
            <el-option
              label="按要求打包"
              :value="1">
            </el-option>
          </el-select>
        </el-form-item>
        <template v-if="form.packKind == 1">
          <el-form-item label="打包要求">
            <el-button size="mini" type="green" @click="addPackRequire">增加</el-button>
            <el-table border :data="packRequireList" size="mini">
              <el-table-column label="包数" prop="packNum">
                <template slot-scope="{row}">
                  <el-input
                    type="number"
                    @keyup.native="proving($event)"
                    v-model="row.packNum"
                    size="mini"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="每包数量" prop="countNum">
                <template slot-scope="{row}">
                  <el-input
                    @keyup.native="proving($event)"
                    type="number"
                    v-model="row.countNum"
                    size="mini"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="总数">
                <template slot-scope="{row}">
                  <span>{{ parseInt(row.packNum) * parseInt(row.countNum) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </template>
    </el-card>
    <el-tabs>
      <el-tab-pane label="物料信息">
        <el-card>
          <div class="box-content">
            <el-button size="mini" type="green" @click="addMaterial(1)">增加辅料</el-button>
            <el-button size="mini" type="green" @click="addMaterial(2)">增加纸张</el-button>
            <el-table :data="form.materialList" border size="mini" style="margin-top: 20px">
              <el-table-column label="物料名称" prop="mtName"></el-table-column>
              <el-table-column label="物料数量" prop="materialQty">
                <template slot-scope="{row}">
                  <el-input size="mini" type="number" v-model="row.materialQty"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="物料备注" prop="materialMemo">
                <template slot-scope="{row}">
                  <el-input size="mini" type="textarea" v-model="row.materialMemo"></el-input>
                </template>
              </el-table-column>
              <el-table-column width="80px" label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="deleteMaterial(scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="发货/付款信息">

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span class="box-header-title">发货信息</span> &nbsp;&nbsp;
            <template v-if="!editFlag">
              <el-button
                size="mini"
                type="primary"
                @click="addressDialog">选择收货地址
              </el-button>&nbsp;&nbsp;
              <el-button size="mini" v-if="addressType == 1" @click="addAddressItem">增加地址</el-button>
            </template>
            <el-form
              :model="form"
              :rules="rules"
              :inline="true"
              label-width="100px"
              label-position="right"
              size="mini"
              style="display: initial">
              <el-form-item label="交货时间" class="itemlabel" prop="deliverDate">
                <el-date-picker
                  v-model="form.deliverDate"
                  type="datetime"
                  value-format='yyyy-MM-dd HH:mm:ss'
                  placeholder="选择日期时间"
                  align="right"
                  :picker-options="pickerOptions"
                  style="margin-top: 5px">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button
                  style="margin-top: 5px"
                  @click="calcSendDate">计算时间
                </el-button>
              </el-form-item>
            </el-form>
              <template v-if="!editFlag">
              <el-input type="textarea" size="mini" style="width: 50%" placeholder="粘贴地址" v-model="parseAddress"
                        clearable></el-input>
              <el-button size="mini" type="green" @click="parseAddressBtn">识别</el-button>
            </template>
            <i class="box-header-icon el-icon-caret-top" @click="unfold($event,'shippingInfo',2)"></i>
          </div>
          <div class="box-content" id="shippingInfo">
            <template v-if="!editFlag">
              <el-table
                :header-cell-style="{background:'#eef1f6',color:'#606266'}"
                class="tb-edit"
                :data="sendAddressList"
                style="width: 100%"
                size="mini"
                border
                highlight-current-row
                @row-click="currentAddress">
                <el-table-column
                  prop="linkMan"
                  label="联系人"
                  width="100px"
                  show-overflow-tooltip>
                  <template scope="scope">
                    <el-input
                      size="small"
                      v-model="scope.row.linkMan"
                      @change="handleEdit(scope.$index, scope.row)"></el-input>
                    <span>{{ scope.row.linkMan }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="linkPhone"
                  label="联系电话"
                  width="150px"
                  show-overflow-tooltip>
                  <template scope="scope">
                    <el-input
                      size="small"
                      v-model="scope.row.linkPhone"
                      @change="handleEdit(scope.$index, scope.row)"></el-input>
                    <span>{{ scope.row.linkPhone }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="发货方式"
                  width="200px"
                  show-overflow-tooltip>
                  <template scope="scope">
                    <el-select
                      size="small"
                      v-model="scope.row.sendKind"
                      filterable
                      placeholder="请选择"
                      style="width: 120px">
                      <template v-if="!scope.row.sendType">
                        <el-option
                          v-for="item in sendKinds"
                          :key="item.id"
                          :label="item.modeName"
                          :value="item.modeName">
                        </el-option>
                      </template>
                      <template v-else>
                        <el-option
                          v-for="item in sendKinds"
                          :key="item.id"
                          :label="item.logisticName"
                          :value="item.logisticName">
                        </el-option>
                      </template>
                    </el-select>
                    <el-checkbox
                      style="width: 60px"
                      v-model="scope.row.sendType"
                      @change="chooseLogistics(scope.row)">物流
                    </el-checkbox>
                    <span>{{ scope.row.sendKind }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="省市区"
                  width="200px"
                  show-overflow-tooltip>
                  <template scope="scope">
                    <el-cascader
                      style="width: 90%"
                      size="mini"
                      filterable
                      :options="option"
                      v-model="addressOption[scope.$index]"
                      @change="changeAddress($event,scope.$index)"
                    >
                    </el-cascader>
                    <span>{{ scope.row.sendProvince }}-{{ scope.row.sendCity }}-{{
                        scope.row.sendDistrict
                      }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="sendAddress"
                  label="详细地址"
                  show-overflow-tooltip>
                  <template scope="scope">
                    <el-input
                      size="small"
                      v-model="scope.row.sendAddress"></el-input>
                    <span>{{ scope.row.sendAddress }}</span>
                  </template>
                </el-table-column>
                <el-table-column width="80px" label="操作">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      @click="deleteAddressItem(scope.$index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
            <template v-else>
              <delivery-notice ref="deliveryNotice" :type="1"></delivery-notice>
            </template>
          </div>
        </el-card>
        <el-form :rules="rules" :model="form" label-width="100px" label-position="right" size="mini">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
                  <span class="box-header-title">价格信息</span>
              <i class="box-header-icon el-icon-caret-top" @click="unfold($event,'priceInfo',2)"></i>
            </div>
            <div class="box-content" id="priceInfo">
              <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item
                        label="总金额"
                        prop="orderMoneyTotal">
                        <el-input
                          v-model="form.orderMoneyTotal"
                          auto-complete="off"
                          type="number"
                          placeholder="请输入总金额"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="付款方式">
                        <el-table
                          :data="payType"
                          ref="payTypeTable"
                          class="tb-edit"
                          size="mini"
                          style="width: 450px;margin-top: 5px"
                          :show-summary="true"
                          :summary-method="getSummaries"
                          border
                          highlight-current-row>
                          <el-table-column
                            label="付款方式"
                            width="120"
                            prop="name">
                          </el-table-column>
                          <el-table-column
                            prop="value"
                            label="金额"
                            width="120">
                            <template scope="scope">
                              <el-input
                                size="small"
                                type="number"
                                v-model="scope.row.value"></el-input>
                              <span>{{ scope.row.value }}</span>
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="guarantee"
                            label="担保人">
                            <template scope="scope">
                              <el-input
                                size="small"
                                v-model="scope.row.guarantee"></el-input>
                              <span>{{ scope.row.guarantee }}</span>
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-form-item>
                    </el-col>
                  </el-row>
            </div>
          </el-card>

        </el-form>
      </el-tab-pane>
    </el-tabs>
    </el-form>
    <el-dialog append-to-body :visible.sync="chooseDialog">
      <select-accessories v-if="chooseType == 1" :isChoose="true" @chooseAccessories='chooseAccessories'></select-accessories>
      <select-paper-info v-else-if="chooseType == 2" :isChoose="true" @choosePaper='choosePaper'></select-paper-info>
    </el-dialog>

    <!--    增加地址-->
    <Addressdny :append="true" ref="address"  :is-choose="true" @chooseAddress='chooseAddress'></Addressdny>
  </el-dialog>
</template>

<script>
import {getDictTypeInfo} from "@/api/productFile/partWorkProcessInfo";
import {CodeToText, regionData, TextToCode} from "element-china-area-data";
import {
  addAndCommitPrintOrder,
  addPrintOrder,
  calcOrderSendDate, getLogisticsInfoList, getshipAreaListInfo,
  getshipModeListInfo,
  orderFormToken,
  parseAddress,
  getDetailPrintOrder, updatePrintOrder, editAndCommitPrintOrder,
} from "@/api/order/orderDetail";
import SelectAccessories from "@/views/select/accessoriesInfo";
import SelectPaperInfo from "@/views/select/paperInfo";
import Addressdny from "@/components/Dialog/Addressdny";
import DeliveryNotice from "@/components/deliveryNotice/deliveryNotice";
import {checkCompleteDispatchOrder} from "@/api/order/tobeReviewed";

const form = {
  /* 订单信息*/
  businessKind: 2,
  fileDescription: '',
  originFileLink: '',
  orderStatePrePay: '',
  voidFlag: '',
  orderState: '', // 订单状态
  orderName: '', // 订单名称
  idProduct: '', // 产品ID
  idClient: '', // 客户id
  clientName: '', // 客户名称
  productName: '', // 产品类型
  productSize: '', // 产品规格
  orderQty: '', // 订单印量
  kindCount: '', // 款数
  printRequire: '', // 印刷要求
  cutKind: '', // 成品裁切
  packRequire: '', // 打包要求
  boxRequire: '', // 包装要求
  packKind: 0, // 打包方式 0均匀打包、1按要求打包
  orderMemo: '', // 订单备注
  orderType: '', // 订单类型
  sendMemo: '', // 发货备注
  deliverDate: '', // 交货日期
  paperRequireFlag: 0,
  /* 发货信息*/
  sendAddressList: [],

  /* 价格信息*/
  orderMoneyTotal: 0, // 总金额
  orderPrice: 0, // 订单价格
  orderMoneyPre: 0, // 订单定金
  orderMoneyPrint: 0, // 印工金额
  orderMoneyProcess: 0, // 后工金额
  orderMoneySend: '', // 订单运费
  payKind: '', // 付款方式

  // 部件信息
  partList: [],
  // 物料信息
  materialList: [],
  versionCode:'',
}
const materialItem = {
  idMaterial:"",
  mtName:'',
  materialQty:'',
  materialMemo:'',
  materialFlag:'',
}
const sendAddressInfo = {
  linkMan: '', // 联系人
  linkPhone: '', // 联系电话
  sendProvince: '', // 发货地址省
  sendCity: '', // 发货地址市
  sendDistrict: '', // 发货地址区
  sendAddress: '', // 详细地址
  sendKind: '', // 发货方式
  sendRegion: '', // 发货区域
  addressQty: '', // 发货数量
  sendType: false
}
const packrequire = {
  packNum: 0,
  countNum: 0
}
export default {
  name: "materialDetail",
  components: {DeliveryNotice, Addressdny, SelectPaperInfo, SelectAccessories},
  props: {
    appendFlag: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 验证金额
    const validateMoney = (rule, value, callback) => {
      // console.log(rule)
      // console.log(value)
      if (value == null) {
        callback(new Error('金额不能为空'))
      } else if ((value + '').indexOf('.') == -1) {
        if (typeof value === 'string') {
          value = Number(value)
        }
        value = (value).toFixed(2) // 不足补位
        var name = rule.fullField
        this.form[name] = value
        callback()
      } else if (value.split('.').length > 2) {
        callback(new Error('输入正确格式的金额')) // 防止输入多个小数点
      } else {
        value = Math.round(value * Math.pow(10, 2)) / Math.pow(10, 2) // 四舍五入
        value = Number(value).toFixed(2) // 不足补位
        var name = rule.fullField
        this.form[name] = value
        callback()
      }
    }
    return {
      materialDialog: false,
      editFlag: false, // 编辑标记
      seeFlag: false, // 查看标记
      versionCode:'',
      idOrder: '',
      form: Object.assign({}, form),
      formToken: '',

      // 物料信息
      chooseDialog: false,
      chooseType: 1,

      packingMethodOptions: [],
      packRequireList: [], // 打包要求列表

      // 付款方式
      payType: [
        {
          id: 0,
          name: '现金收款',
          value: '0',
          guarantee: ''
        },
        {
          id: 1,
          name: '物流代收',
          value: '0',
          guarantee: ''
        },
        {
          id: 2,
          name: '担保人',
          value: '0',
          guarantee: ''
        },
        {
          id: 3,
          name: '预存',
          value: '0',
          guarantee: ''
        },
        {
          id: 4,
          name: '预收款',
          value: '0',
          guarantee: ''
        }
      ],
      sums: '',

      // 时间选项快捷方式
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '明天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }],
        disabledDate(time) {
          // 如果没有后面的-8.64e7就是不可以选择今天的
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      addressType: 1,
      // 发货信息
      sendAddressList: [],
      // 省市区选项
      addressOption: [],
      // 发货方式
      sendKinds: [],
      // 发货区域
      shipAreaList: [],
      option: regionData,
      selectedOptions: '',
      addressVisible: false,
      // 解析地址
      parseAddress: '',

      // 点击等待
      clickLoading: false,
      // 验证规则
      rules: {
        orderName: [{required: true, trigger: 'blur', message: '请填写订单名称'}],
        orderMoneyTotal: [{required: true, trigger: 'blur', validator: validateMoney}],
        deliverDate: [{required: true, trigger: 'blur', message: '请选择交货时间'}]
      }

    }
  },
  mounted() {
    const _that = this
    _that.getDictInfo('PrintRequire')
    _that.getDictInfo('OrderPrintDesc')
    _that.getDictInfo('PackingMethod')
    _that.getSendKind()
    _that.getToken()
  },
  methods: {
    getOrderInfo() {
      const _that = this
      var data = {
        'idOrder': _that.idOrder,
      }
      getDetailPrintOrder(data).then(res=>{
        console.log(res);
        var data = res.data
        _that.form = {
          /* 订单信息*/
          businessKind: data.businessKind,
          fileDescription: data.fileDescription,
          originFileLink: data.originFileLink,
          orderState: data.orderState,
          versionCode: _that.versionCode,
          stateMemo: data.stateMemo,
          orderStatePrePay: data.orderStatePrePay,
          voidFlag: data.voidFlag,
          orderName: data.orderName, // 订单名称
          orderCode: data.orderCode,
          idProduct: data.idProduct, // 产品ID
          idClient: data.idClient, // 客户id
          clientName: data.clientName, // 客户名称
          productName: data.productName, // 产品类型
          productSize: data.productSize, // 产品规格
          orderQty: data.orderQty, // 订单印量
          kindCount: data.kindCount, // 款数
          printRequire: data.printRequire, // 印刷要求
          cutKind: (data.cutKind).toString(), // 成品裁切
          packKind: data.packKind,
          boxRequire: data.boxRequire,
          orderMemo: data.orderMemo, // 订单备注
          orderType: data.orderType, // 订单类型
          sendMemo: data.sendMemo, // 发货备注
          deliverDate: data.deliverDate, // 交货日期
          /* 发货信息*/
          sendAddressList: data.sendAddressList,

          /* 价格信息*/
          orderMoneyTotal: data.orderMoneyTotal, // 总金额
          orderPrice: data.orderPrice, // 订单价格
          orderMoneyPre: data.orderMoneyPre, // 订单定金
          orderMoneyPrint: data.orderMoneyPrint, // 印工金额
          orderMoneyProcess: data.orderMoneyProcess, // 后工金额
          orderMoneySend: data.orderMoneySend, // 订单运费
          payKind: data.payKind, // 付款方式
          paperRequireFlag: data.paperRequireFlag,

          // 部件信息
          partList: [],
          materialList: data.materialList,
          deliverInformList: data.deliverInformList
        }
        if (data.packRequire) {
          var packrequire = data.packRequire.split('+')
          // console.log(packrequire);
          var packrequireList = []
          packrequire.forEach(item => {
            var packrequireItem = {
              packNum: item.split('*')[0],
              countNum: item.split('*')[1]
            }
            packrequireList.push(packrequireItem)
          })
          _that.packrequireList = packrequireList
        }
        _that.partListNew = data.partList
        _that.sendAddressList = data.sendAddressList;
        (data.sendAddressList).forEach(address => {
          var addressOption = []
          // if (address.sendProvince) {
          //   addressOption.push(TextToCode[address.sendProvince].code)
          // }
          // if (address.sendCity) {
          //   addressOption.push(TextToCode[address.sendProvince][address.sendCity].code)
          // }
          // if (address.sendDistrict) {
          //   addressOption.push(TextToCode[address.sendProvince][address.sendCity][address.sendDistrict].code)
          // }
          _that.addressOption.push(addressOption)
        })
        data.partList.forEach(item => {
          _that.partProcessList.push(item.processList)
        })
        if (data.printRequire != '' && data.printRequire != null) {
          _that.printRequireOption = data.printRequire.split(',')
        }
        // 付款方式
        if (data.payKind) {
          var paykindString = data.payKind
          var paykindList = paykindString.split('+')
          paykindList.forEach(item => {
            var itemList = item.split(':')
            _that.payType[itemList[0]].value = itemList[2]
            if (itemList[0] == 2) {
              _that.payType[itemList[0]].guarantee = itemList[3]
            }
          })
        }
        if(_that.editFlag){
          _that.$nextTick(() => {
            _that.$refs.deliveryNotice.currentIdClient = data.idClient
            // console.log(_that.$refs.deliveryNotice.currentIdClient);
            _that.$refs.deliveryNotice.currentIdOrder = data.id
            _that.$refs.deliveryNotice.openNotices()
          })
        }

      })
    },

    // 获取字典
    getDictInfo(typeText) {
      const _that = this
      var data = {
        'dictTypeText': typeText
      }

      // console.log(data)
      getDictTypeInfo(data).then(response => {
        // console.log(response)
        const data = response.data
        if (typeText == 'PrintRequire') {
          _that.printRequireOptions = data
        } else if (typeText == 'OrderPrintDesc') {
          _that.orderPrintOptions = data
        } else if (typeText == 'PackingMethod') {
          _that.packingMethodOptions = data
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 添加打包要求
    addPackRequire() {
      const _that = this
      var packRequireItem = Object.assign({}, packrequire)
      _that.packRequireList.push(packRequireItem)
    },
    // 禁止输入小数，负数
    proving(e) {
      var keynum = window.event ? e.keyCode : e.which // 获取键盘码
      if (keynum == 189 || keynum == 109) { // 禁止输入负数
        this.$message.warning('禁止输入负数')
        e.target.value = 0
      }
      if (keynum == 110 || keynum == 190) { // 禁止输入负数
        this.$message.warning('禁止输入小数')
        e.target.value = ''
      }
    },

    /**
     * 物料信息
     **/
    // 增加物料
    addMaterial(type) {
      //type 1 选择辅料 2 选择纸张
      const _that = this
      _that.chooseDialog = true
      _that.chooseType = type
    },
    chooseAccessories(row) {
      const _that = this
      _that.chooseDialog = false
      _that.form.materialList.push({
        idMaterial: row.id,
        mtName: row.materialName,
        materialQty: '',
        materialMemo: '',
        materialFlag:0,
      })
    },
    choosePaper(row){
      const _that = this
      _that.chooseDialog = false
      _that.form.materialList.push({
        idMaterial: row.id,
        mtName: row.paperName,
        materialQty: '',
        materialMemo: '',
        materialFlag: 1,
      })
    },

    // 删除物料信息
    deleteMaterial(index) {
      this.form.materialList.splice(index, 1)
    },
    addressDialog() {
      const _that = this
      // _that.addressVisible = true
      // _that.$nextTick(function() {
      this.$refs.address.outerVisible = true
      _that.$refs.address.idClient = _that.form.idClient
      // this.$refs.address.clientName = name
      var pageNum = 1
      _that.$refs.address.getInfo(pageNum, '')
      _that.$refs.address.searchVal = ''
      // })
    },
    // 选择地址
    chooseAddress(row) {
      var sendAddressItem = Object.assign({}, sendAddressInfo)

      sendAddressItem.sendKind = row.shipModeName
      sendAddressItem.sendRegion = row.shipArea
      sendAddressItem.linkMan = row.receiveMan
      sendAddressItem.linkPhone = row.receivePhone
      sendAddressItem.sendAddress = row.address
      sendAddressItem.sendProvince = row.province
      sendAddressItem.sendCity = row.city
      sendAddressItem.sendDistrict = row.area

      var addressOption = []
      if (row.province) {
        addressOption.push(TextToCode[row.province].code)
        addressOption.push(TextToCode[row.province][row.city].code)
        addressOption.push(TextToCode[row.province][row.city][row.area].code)
      }

      if (this.addressType == 0) {
        this.sendAddressList.splice(0, 1, sendAddressItem)

        this.addressOption.splice(0, 1, addressOption)
        // this.sendAddressList[0] = sendAddressItem
        // console.log(this.sendAddressList)
      } else {
        this.sendAddressList.push(sendAddressItem)

        this.addressOption.push(addressOption)
      }
      this.$refs.address.outerVisible = false
    },
    // 增加收货地址
    addAddressItem() {
      var sendAddressItem = Object.assign({}, sendAddressInfo)
      this.sendAddressList.push(sendAddressItem)
      this.addressOption.push([])
      this.getSendKind()
    },
    // 获取发货方式
    getSendKind() {
      var _that = this
      getshipModeListInfo().then(response => {
        // console.log('getSendKind', response)
        _that.sendKinds = response.data
      }).catch(err => {
        // console.log(err)
      })
    },
    // 获取物流档案
    getLogisticsInfo() {
      var _that = this
      var data = {
        params: {
          enable: 1
        }
      }
      getLogisticsInfoList(data).then(response => {
        // console.log('getSendKind', response)
        _that.sendKinds = response.data
      }).catch(err => {
        // console.log(err)
      })
    },
    // 获取发货区域
    getAreaList() {
      var _that = this
      getshipAreaListInfo().then(response => {
        // console.log('shipArea', response)
        const data = response.data
        // //  组合表单数据
        _that.shipAreaList = response.data
        // console.log(_that.shipAreaList);
      }).catch(err => {
        // console.log(err)
      })
    },
    // 选择物流档案
    chooseLogistics(row) {
      const _that = this
      // console.log(row)
      if (row.sendType) {
        _that.getLogisticsInfo()
      } else {
        _that.getSendKind()
      }
    },
    currentAddress(row, event, column) {
      const _that = this
      if (row.sendType) {
        _that.getLogisticsInfo()
      } else {
        _that.getSendKind()
      }
    },

    // 修改省市区
    changeAddress(value, index) {
      var _that = this
      _that.sendAddressList[index].sendProvince = CodeToText[value[0]]
      _that.sendAddressList[index].sendCity = CodeToText[value[1]]
      _that.sendAddressList[index].sendDistrict = CodeToText[value[2]]
    },
    // 删除收货地址
    deleteAddressItem(index) {
      this.sendAddressList.splice(index, 1)
      this.addressOption.splice(index, 1)
    },
    // 解析地址
    parseAddressBtn() {
      const _that = this
      if (!_that.parseAddress) {
        _that.$message.warning('请粘贴地址')
        return
      }
      var data = {
        'address': _that.parseAddress
      }
      parseAddress(data).then(response => {
        console.log(response)
        var data = response.data[0]
        var sendAddressItem = Object.assign({}, sendAddressInfo)
        sendAddressItem.linkMan = data.name
        if (data.mobile) {
          sendAddressItem.linkPhone = data.mobile
        }
        if (data.phone) {
          sendAddressItem.linkPhone = data.phone
        }
        sendAddressItem.sendProvince = data.province
        sendAddressItem.sendCity = data.city
        sendAddressItem.sendDistrict = data.county
        sendAddressItem.sendAddress = data.details
        _that.sendAddressList.push(sendAddressItem)
        var addressOption = []

        if (data.province) {
          addressOption.push(TextToCode[data.province].code)
          if (data.city) {
            addressOption.push(TextToCode[data.province][data.city].code)
            if (data.county) {
              addressOption.push(TextToCode[data.province][data.city][data.county].code)
            }
          }
        }
        _that.addressOption.push(addressOption)
        this.getSendKind()

      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 计算时间
    calcSendDate() {
      var _that = this

      if (_that.sendAddressList.length <= 0) {
        _that.$message.error('请填写收货地址')
        return
      }
      // if (_that.orderCategory == 1) {
      if (_that.sendAddressList[0].sendKind == undefined || _that.sendAddressList[0].sendKind == null || _that.sendAddressList[0].sendKind == '') {
        _that.$message.error('请选择发货方式')
        return
      }
      // }
      var execParams = {
        'sendKind': _that.sendAddressList[0].sendKind,
        'deliverDate': _that.form.deliverDate
      }

      var data = {
        'params': execParams
      }
      calcOrderSendDate(data).then(response => {
        // console.log(response)
        const data = response.data
        _that.form.deliverDate = data.itemData.deliverDate
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 表格合计
    getSummaries(param) {
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        // 如果是第一列，则最后一行展示为“总计”两个字
        if (index === 0) {
          sums[index] = '总计'
          // 如果是最后一列，索引为列数-1，则显示计算总和
        } else if (index === 1) {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          } else {
            sums[index] = 'N/A'
          }
          // 如果是除了第一列和最后一列的其他列，则显示为空
        } else {
          sums[index] = ''
        }
      })
      // console.log(sums)
      this.sums = sums[1]
      return sums
    },

    getToken() {
      orderFormToken().then(res => {
        this.formToken = res.data
      })
    },

    // 增加物料订单
    addMaterialOrder(type){
      const _that = this
      _that.$refs['form'].validate(valid=>{
        if(valid){
          if(_that.form.materialList.length<=0){
            _that.$message.error('物料信息不能为空')
            return
          }
          if (_that.form.deliverDate === '' || _that.form.deliverDate == null) {
            _that.$message.error('交货时间不能为空')
            return
          }
          // 付款方式
          var selectionArr = []
          for (let j = 0; j < _that.payType.length; j++) {
            if (_that.payType[j].value > 0) {
              if (_that.payType[j].id == 2) {
                if (!_that.payType[j].guarantee) {
                  _that.$message.error('担保人不能为空')
                  return
                }
              }
              var selectionString = ''
              selectionString = _that.payType[j].id + ':' + _that.payType[j].name + ':' + _that.payType[j].value + ':' + _that.payType[j].guarantee
              selectionArr.push(selectionString)
            }
          }
          _that.form.payKind = selectionArr.join('+')
          if (parseInt(_that.sums) < parseInt(_that.form.orderMoneyTotal)) {
            _that.$message.error('付款方式总计金额不能小于总金额')
            return
          }
          // 总金额判断
          if (_that.form.orderMoneyTotal == 0) {
            _that.$message.warning('订单金额不能为0')
            return
          } else {
            _that.clickLoading = true
            _that.form.sendAddressList = _that.sendAddressList
            if(type == 1){
              _that.saveOrder()
            }else if (type == 2){
              _that.saveAndPush()
            }else if(type == 3){
              _that.editOrder()
            }else if (type == 4){
              _that.editAndPush()
            }
          }
        }
      })

    },

    // 保存
    saveOrder(){
      const _that = this
      var data = JSON.stringify(_that.form)
      addPrintOrder(data, _that.formToken).then(res =>{
        console.log(res);
        if (res.httpCode == 200) {
          _that.materialDialog = false
          _that.clickLoading = false
          // _that.$store.dispatch('tagsView/delView', _that.tempRoute).then(() => {
          //   _that.$router.push({path: '/order/tobeEditedOrder/0'})
          // })

          _that.$emit('requestSuccess','')
        } else {
          _that.getToken()
          _that.clickLoading = false
        }
      }).catch(err => {
        _that.getToken()
        _that.clickLoading = false
        // console.log(err)
        _that.$message.error(err)
      })
    },
    // 保存并提交
    saveAndPush(){
      const _that = this
      var data = JSON.stringify(_that.form)
      addAndCommitPrintOrder(data, _that.formToken).then(res =>{
        console.log(res);
        if (res.httpCode == 200) {
          _that.materialDialog = false
          _that.clickLoading = false
          // _that.$store.dispatch('tagsView/delView', _that.tempRoute).then(() => {
          //   _that.$router.push({path: '/order/tobeEditedOrder/0'})
          // })
          _that.$emit('requestSuccess','')
        } else {
          _that.getToken()
          _that.clickLoading = false
        }
      }).catch(err => {
        _that.getToken()
        _that.clickLoading = false
        // console.log(err)
        _that.$message.error(err)
      })
    },

    //修改
    editOrder(){
      const _that = this
      _that.form.id = _that.idOrder
      var data = JSON.stringify(_that.form)
      updatePrintOrder(data, _that.formToken).then(res =>{
        console.log(res);
        if (res.httpCode == 200) {
          _that.materialDialog = false
          _that.clickLoading = false
          // _that.$store.dispatch('tagsView/delView', _that.tempRoute).then(() => {
          //   _that.$router.push({path: '/order/tobeEditedOrder/0'})
          // })

          _that.$emit('requestSuccess','')
        } else {
          _that.getToken()
          _that.clickLoading = false
        }
      }).catch(err => {
        _that.getToken()
        _that.clickLoading = false
        // console.log(err)
        _that.$message.error(err)
      })
    },
    editAndPush(){
      const _that = this
      _that.form.id = _that.idOrder
      var data = JSON.stringify(_that.form)
      editAndCommitPrintOrder(data).then(res =>{
        console.log(res);
        if (res.httpCode == 200) {
          _that.materialDialog = false
          _that.clickLoading = false
          // _that.$store.dispatch('tagsView/delView', _that.tempRoute).then(() => {
          //   _that.$router.push({path: '/order/tobeEditedOrder/0'})
          // })

          _that.$emit('requestSuccess','')
        } else {
          _that.getToken()
          _that.clickLoading = false
        }
      }).catch(err => {
        _that.getToken()
        _that.clickLoading = false
        // console.log(err)
        _that.$message.error(err)
      })
    },

    // 展开收起
    unfold: function (e, data, type) {
      const dv = document.getElementById(data)

      var pv = dv.parentNode
      if (dv.className == 'show') {
        dv.removeAttribute('class')
        pv.className = 'el-card__body'
        if (type == 2) {
          e.target.className = 'box-header-icon el-icon-caret-top'
        } else {
          pv.parentNode.children[0].children[0].children[1].className = 'box-header-icon el-icon-caret-top'
        }
      } else {
        dv.setAttribute('class', 'show')
        pv.className = 'hideContent'
        if (type == 2) {
          e.target.className = 'box-header-icon el-icon-caret-bottom'
        } else {
          pv.parentNode.children[0].children[0].children[1].className = 'box-header-icon el-icon-caret-bottom'
        }
      }
    },

  }
}
</script>

<style scoped>
::v-deep .el-dialog__body{
  padding-top: 10px;
}
::v-deep .el-card__header {
  padding: 5px 20px;
}
::v-deep .el-form-item__content{
  margin-left: 10px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}
.box-card {
  margin-bottom: 10px;
}

.box-header-title {
  line-height: 36px;
  font-size: 17px;
  color: #666;
}

.box-header-right {
  float: right;
  color: #20a0ff;
  line-height: 36px;
  cursor: pointer;
  margin-right: 10px;
}

.box-header-icon {
  float: right;
  color: #20a0ff;
  line-height: 36px;
  cursor: pointer;
}

.show {
  display: none;
}

.hideContent {
  padding: 0;
}
.tb-edit .el-select, .tb-edit .el-checkbox {
  display: inline-block;
}

.tb-edit .el-input, .tb-edit .el-select, .tb-edit .el-cascader, .tb-edit .el-checkbox {
  display: none
}

.tb-edit .current-row .el-input, .tb-edit .current-row .el-checkbox, .tb-edit .current-row .el-select, .tb-edit .current-row .el-cascader {
  display: block
}

.tb-edit .current-row .el-input + span, .tb-edit .current-row .el-checkbox + span, .tb-edit .current-row .el-select + span, .tb-edit .current-row .el-cascader + span {
  display: none
}

.processDialog ::v-deep .el-dialog__body {
  padding: 0;
}

::v-deep .el-card__body {
  padding: 10px;
}
</style>
