<template>
  <div>
<!--  <el-dialog title="编辑发货通知" :close-on-click-modal="false" :visible.sync="noticeVisible" width="1200px" class="addressDialog">-->
    <el-form inline v-if="type == 0">
      <el-form-item label="发货备注" style="width: 1000px">
        <el-input type="textarea" v-model="sendMemo" maxlength="150" show-word-limit style="width: 900px"></el-input>
      </el-form-item>
      <el-button size="mini" type="green" @click="saveMemo">保存</el-button>
    </el-form>
    <span class="textCount" v-if="type == 0">已入库总包数:{{inStockBoxCount}}</span>
    <span class="textCount" v-if="type == 0">未发货包数:{{waitSendBoxCount}}</span>
    <el-tabs v-model="activeTabName" :class="type == 0 ?'':'tabShow'">
      <el-tab-pane name="first" :label="type == 0 ?'未发货' :''">
        <div class="filter-container">
          <el-button
            size="mini"
            type="primary"
            @click="addressDialog">选择收货地址
          </el-button>&nbsp;&nbsp;
          <el-button size="mini" @click="addAddressItem">增加地址</el-button>
          <div class="textShow" v-if="type == 0">
            <label>订单状态：</label>
            <span>{{ addressDialogInfo.orderState }}</span>
          </div>
          <!--        <div class="textShow">-->
          <!--          <label>入库包数：</label>-->
          <!--          <span>{{}}</span>-->
          <!--        </div>-->
        </div>
        <el-card v-for="(item,index) in sendAddressList" :key="index">
          <div class="addressCard">
            <template v-if="item.edit">
              <el-input type="textarea" size="mini" style="width: 50%" placeholder="粘贴地址" v-model="parseAddress" clearable></el-input>
              <el-button size="mini" type="green" @click="parseAddressBtn(index)">智能识别</el-button>
            </template>
            <el-form inline :disabled="!item.edit">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="联系人">
                    <el-input
                      size="small"
                      v-model="item.linkMan"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="联系电话">
                    <el-input
                      size="small"
                      v-model="item.linkPhone"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="发货方式">
                    <el-select size="small" v-model="item.sendKind" filterable placeholder="请选择" style="width: 110px">
                      <template  v-if="!item.sendType || item.sendType == undefined" >
                        <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="item.sendType" @change="chooseLogistics(item)">物流</el-checkbox>

                  </el-form-item>
                </el-col>
                <!--              <el-col :span="5">-->
                <!--                <el-form-item label="发货区域">-->
                <!--                  <el-select size="small" v-model="item.sendRegion" placeholder="请选择" style="width: 135px">-->
                <!--                    <el-option-->
                <!--                      v-for="item in shipAreaList"-->
                <!--                      :key="item.id"-->
                <!--                      :label="item.areaName"-->
                <!--                      :value="item.areaName">-->
                <!--                    </el-option>-->
                <!--                  </el-select>-->
                <!--                </el-form-item>-->
                <!--              </el-col>-->
                <el-col :span="6">
                  <el-form-item label="发货数量">
                    <el-input
                      style="width: 135px"
                      type="number"
                      size="small"
                      v-model="item.needDeliverQty"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="省市区">
                    <el-cascader
                      style="width: 300px"
                      size="mini"
                      filterable
                      :options="option"
                      v-model="addressOption[index]"
                      @change="changeAddress($event,index)"
                    >
                    </el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="详细地址">
                    <el-input
                      size="small"
                      type="textarea"
                      v-model="item.sendAddress"
                      style="width: 455px"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="bottom clearfix">
            <el-button
              size="mini"
              type="danger"
              @click="deleteAddressItem(item,index)">
              删除
            </el-button>
            <el-button
              v-if="!item.edit"
              type="primary"
              size="mini"
              @click="editAddressItem(item)"
            >
              编辑
            </el-button>
            <el-button
              v-else
              type="success"
              size="mini"
              @click="confirmEdit(item)"
            >
              保存
            </el-button>
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane name="second" label="已发货" v-if="type == 0">

        <el-table
          :data="sendAddressListBySend"
          size="mini"
          ref="deliveryItemTable"
          row-key="id"
          border
          style="margin-bottom: 20px">
          <template v-for="column in deliveryColumns">

            <el-table-column
              v-if="column.label =='状态'"
              :key="column.field"
              :prop="column.field"
              :label="column.label"
              :width="column.width"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                <template v-if="row.voidFlag == 1">
                  <el-tag size="mini" type="info">已作废</el-tag>
                </template>
                <template v-else>
                  <el-tag size="mini" v-if="row[column.field] == '0'" type="warning">待入库</el-tag>
                  <el-tag size="mini" v-if="row[column.field] == '1'">待发货</el-tag>
                  <el-tag size="mini" v-if="row[column.field] == '2'" type="success">已发货</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              v-else
              :key="column.field"
              :prop="column.field"
              :label="column.label"
              :width="column.width"
              show-overflow-tooltip>
            </el-table-column>
          </template>
        </el-table>
      </el-tab-pane>
      <el-tab-pane name="third" label="已作废" v-if="type == 0">

        <el-table
          :data="sendAddressListByDisable"
          size="mini"
          ref="deliveryItemTable"
          row-key="id"
          border
          style="margin-bottom: 20px">
          <template v-for="column in deliveryColumns">

            <el-table-column
              v-if="column.label =='状态'"
              :key="column.field"
              :prop="column.field"
              :label="column.label"
              :width="column.width"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                <template v-if="row.voidFlag == 1">
                  <el-tag size="mini" type="info">已作废</el-tag>
                </template>
                <template v-else>
                  <el-tag size="mini" v-if="row[column.field] == '0'" type="warning">待入库</el-tag>
                  <el-tag size="mini" v-if="row[column.field] == '1'">待发货</el-tag>
                  <el-tag size="mini" v-if="row[column.field] == '2'" type="success">已发货</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              v-else
              :key="column.field"
              :prop="column.field"
              :label="column.label"
              :width="column.width"
              show-overflow-tooltip>
            </el-table-column>
          </template>
          <el-table-column label="作废原因" prop="returnMemo" show-overflow-tooltip></el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
<!--  </el-dialog>-->
  <Addressdny ref="address" :append="true" :is-choose="true" @chooseAddress='chooseAddress' ></Addressdny>
  </div>
</template>

<script>
import {CodeToText, regionData, TextToCode} from "element-china-area-data";
import {
  addOrderDeliverInform,
  deleteOrderDeliverInform,
  editOrderDeliverInform,
  getOrderDeliverInform, getOrderFiledValueByName, getshipAreaListInfo, getshipModeListInfo
} from "@/api/order/orderList";
import {calcOrderSendDate, getLogisticsInfoList, parseAddress, updateOrderSendMemo} from "@/api/order/orderDetail";
import Addressdny from "@/components/Dialog/Addressdny";


const sendAddressInfo = {
  linkMan: '', // 联系人
  linkPhone: '', // 联系电话
  sendProvince: '', // 发货地址省
  sendCity: '', // 发货地址市
  sendDistrict: '', // 发货地址区
  sendAddress: '', // 详细地址
  sendKind: '', // 发货方式
  sendRegion: '', // 发货区域
  needDeliverQty: '', // 发货数量
  edit: true,
  orderType: 0,
  sendType: false,
  versionCode: ''
}
const deliveryItems = [
  {
    label: '状态', field: 'sendState', width: '100'
  },
  {
    label: '联系人', field: 'linkMan', width: '100'
  },
  {
    label: '联系电话', field: 'linkPhone', width: '120'
  },
  {
    label: '发货方式', field: 'sendKind', width: '130'
  },
  {
    label: '已发货包数', field: 'sendedBoxCount', width: '130'
  },
  {
    label: '发货数量', field: 'needDeliverQty', width: '100'
  },
  {
    label: '发货地址省', field: 'sendProvince', width: '80'
  },
  {
    label: '发货地址市', field: 'sendCity', width: '80'
  },
  {
    label: '发货地址区', field: 'sendDistrict', width: '90'
  },
  {
    label: '详细地址', field: 'sendAddress', width: ''
  }
]
export default {
  name: 'deliveryNotice',
  components: {Addressdny},
  props: {
    // type 1 编辑订单用
    type: {
      type: Number,
      default: 0
    },
    deliverDate: String,
    deliverTime: String
  },
  data() {
    return {
      deliverDateReal:this.deliverDate,
      deliverTimeReal:this.deliverTime,
      noticeVisible: false,
      currentIdOrder: '',
      sendMemo:'',
      currentIdClient: '',
      inStockBoxCount: 0,
      waitSendBoxCount: 0,
      // 发货信息
      sendAddressList: [],
      sendAddressListBySend: [],
      sendAddressListByDisable: [],
      // 省市区选项
      addressOption: [],
      // 发货方式
      sendKinds: [],
      // 发货区域
      shipAreaList: [],
      option: regionData,
      addressDialogInfo: {
        orderState: '',
        boxCount: ''
      },
      activeTabName: 'first',
      deliveryColumns: Object.assign([], deliveryItems),

      parseAddress: ''
    }
  },
  methods: {
    sendKindChange(val){
      // console.log(val);
      var _that = this
      var execParams = {}
      if(!_that.deliverDateReal){
        var deliverDate = "";
      }else {
        var deliverDate = _that.deliverDateReal+" "+_that.deliverTimeReal
      }
      execParams = {
        'sendKind': val,
        'deliverDate': deliverDate
      }
      var data = {
        'params': execParams
      }
      calcOrderSendDate(data).then(response => {
        // console.log(response)
        const data = response.data
        if(data.itemData.deliverDate){
          _that.$emit('handleGet',data.itemData.deliverDate)
        }

      }).catch(err => {
        _that.$message.error(err)
      })
    },
    openNotices() {
      var _that = this
      // _that.noticeVisible = true
      _that.activeTabName = 'first'
      _that.addressOption = [];
      _that.sendAddressList = []
      _that.sendAddressListBySend = []
      _that.sendAddressListByDisable = []
      _that.getDeliverInform()
      _that.getOrderFiled()
    },
    getDeliverInform() {
      var _that = this
      var data = {
        idOrder: _that.currentIdOrder,
        available: false
      }
      _that.addressOption = []
      _that.sendAddressList = []
      _that.sendAddressListBySend = []
      _that.sendAddressListByDisable = []
      getOrderDeliverInform(data).then(response => {
        // console.log(response)
        const data = response.data

        data.forEach(item => {
          if (item.voidFlag == 1) {
            _that.sendAddressListByDisable.push(item)
          } else {
            if (item.sendState == 0 || item.sendState == 1) {
              _that.sendAddressList.push(item)
            } else {
              _that.sendAddressListBySend.push(item)
            }
          }
        });
        (_that.sendAddressList).map(item => {
          _that.$set(item, 'edit', false)
          _that.$set(item, 'ordertype', 1)
          // item.edit = false
          // item.ordertype = 1 // 0为新增，1为修改
          return item
        });
        (_that.sendAddressList).forEach(address => {
          var addressOption = []
          if (address.sendProvince) {
            addressOption.push(TextToCode[address.sendProvince].code)
            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)
        })
      }).catch(err => {
      })
    },
    getOrderFiled() {
      var _that = this
      var data = {
        idOrder: _that.currentIdOrder,
        fieldName: 'sendMemo'
      }
      getOrderFiledValueByName(data).then(response =>{
        // console.log(response);
        if(response.data != null){
          _that.sendMemo = response.data
        }else {
          _that.sendMemo = ''
        }

      })
    },
    // 选择收货地址
    addressDialog() {
      var _that = this

      if (!_that.sendAddressList.every(item => item.edit == false)) {
        _that.$message.warning('请先保存')
        return
      }
      this.$refs.address.outerVisible = true
      _that.$refs.address.idClient = _that.currentIdClient
      var pageNum = 1
      _that.$refs.address.getInfo(pageNum, '')
      _that.$refs.address.searchVal = ''
    },
    // 保存
    confirmEdit(row) {
      var _that = this
      // console.log(row)
      // item.needDeliverQty"
      if (row.needDeliverQty.length>9) {
        _that.$message.error('发货数量不能超过9位数')
        return
      }
      if (!row.sendKind) {
        _that.$message.error('请选择发货方式')
        return
      }
      if(!row.sendProvince){
        _that.$message.error('请选择省市区')
        return
      }
      _that.sendKindChange(row.sendKind)
      if (row.orderType == 0) {
        _that.addAddressInfo(row)
      } else {
        console.log('修改了');
        _that.editAddressInfo(row)
      }
    },
    // 添加发货通知
    addAddressInfo(row) {
      var _that = this
      if(row.needDeliverQty == 0 || row.needDeliverQty == null) {
        _that.$confirm('发货数量为空，发货通知将默认为订单印量，是否继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          _that.addAddressInfoSure(row)
        }).catch(() => {
          return
        })
      }else {
        _that.addAddressInfoSure(row)
      }
    },
    addAddressInfoSure(row){
      const _that = this
      var data = {
        'idOrder': _that.currentIdOrder,
        'linkMan': row.linkMan,
        'linkPhone': row.linkPhone,
        'sendProvince': row.sendProvince,
        'sendCity': row.sendCity,
        'sendDistrict': row.sendDistrict,
        'sendAddress': row.sendAddress,
        'needDeliverQty': row.needDeliverQty,
        'sendKind': row.sendKind,
        'sendRegion': row.sendRegion,
        'versionCode': row.versionCode
      }
      var options = {
        'orderDeliverInform': JSON.stringify(data)
      }
      // console.log(data);
      // return
      addOrderDeliverInform(options).then(response => {
        // console.log(response)
        if (response.httpCode == 200) {
          _that.$message({
            message: '添加成功',
            type: 'success'
          })
          row.edit = false
          row.versionCode = response.data.versionCode
          _that.getDeliverInform()
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 修改发货通知
    editAddressInfo(row) {
      var _that = this
      if(row.needDeliverQty == 0 || row.needDeliverQty == null){
        _that.$confirm('发货数量为空，发货通知将默认为订单印量，是否继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          _that.editAddressInfoSave(row)
        }).catch(() => {
          return
        })
      }else {
        _that.editAddressInfoSave(row)
      }
    },
    editAddressInfoSave(row) {
      var _that = this
      // 确定操作
      var data = {
        'id': row.id,
        'idOrder': row.idOrder,
        'linkMan': row.linkMan,
        'linkPhone': row.linkPhone,
        'sendProvince': row.sendProvince,
        'sendCity': row.sendCity,
        'sendDistrict': row.sendDistrict,
        'sendAddress': row.sendAddress,
        'needDeliverQty': row.needDeliverQty,
        'sendKind': row.sendKind,
        'sendRegion': row.sendRegion,
        'versionCode': row.versionCode
      }
      var options = {
        'orderDeliverInform': JSON.stringify(data)
      }
      // console.log(data);
      // return
      editOrderDeliverInform(options).then(response => {
        // console.log(response)
        if (response.httpCode == 200) {
          _that.$message({
            message: '修改成功',
            type: 'success'
          })
          row.edit = false
          row.versionCode = response.data.versionCode
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 选择地址
    chooseAddress(row) {

      this.sendAddressList.map(item => {
        // if (item.edit) {
        item.edit = false
        // }
        return item
      })
      this.parseAddress = ''
      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
      sendAddressItem.needDeliverQty = row.needDeliverQty
      sendAddressItem.edit = true
      sendAddressItem.orderType = 0

      var addressOption = []

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

      this.sendAddressList.push(sendAddressItem)
      this.addressOption.push(addressOption)
      this.$refs.address.outerVisible = false
      this.getSendKind()
    },
    // 增加收货地址
    addAddressItem() {
      // this.sendAddressList.map(item => {
      //     item.edit = false
      //   return item
      // })
      if (!this.sendAddressList.every(item => item.edit == false)) {
        this.$message.warning('请先保存')
        return
      }

      this.parseAddress = ''
      var sendAddressItem = Object.assign({}, sendAddressInfo)
      this.sendAddressList.push(sendAddressItem)
      this.addressOption.push([])

      this.getSendKind()
    },

    // 选择物流档案
    chooseLogistics(row) {
      // console.log(row);
      const _that = this
      if (row.sendType) {
        _that.getLogisticsInfo()
      } else {
        _that.getSendKind()
      }
    },

    // 编辑收货地址
    editAddressItem(row, index) {
      const _that = this
      _that.parseAddress = ''
      row.edit = !row.edit
      if (row.sendType) {
        _that.getLogisticsInfo()
      } else {
        _that.getSendKind()
      }
    },
    // 删除收货地址
    deleteAddressItem(row, index) {
      var _that = this
      _that.parseAddress = ''
      for (let i = 0; i < _that.sendAddressList.length; i++) {
        var item = _that.sendAddressList[i]
        if (item.edit == true) {
          if (item.id != row.id) {
            _that.$message.warning('请先保存')
            return
          }
        }
      }
      _that.addressOption.splice(index, 1)
      if (row.id != undefined) {
        var options = {
          'id': row.id,
          'versionCode': row.versionCode
        }
        deleteOrderDeliverInform(options).then(response => {
          // console.log(response)
          if (response.httpCode == 200) {
            _that.$message({
              message: '删除成功',
              type: 'success'
            })
            _that.getDeliverInform()
          } else {
            _that.$message.error(response.msg)
          }
        }).catch(err => {
          _that.$message.error(err)
        })
      } else {
        _that.sendAddressList.splice(index, 1)
      }
    },
    // 修改省市区
    changeAddress(value, index) {
      // console.log(index);
      // console.log(value)
      var _that = this
      if(value) {
        _that.sendAddressList[index].sendProvince = CodeToText[value[0]]
        _that.sendAddressList[index].sendCity = CodeToText[value[1]]
        _that.sendAddressList[index].sendDistrict = CodeToText[value[2]]
      }
    },
    // 获取发货方式
    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
      }).catch(err => {
        console.log(err)
      })
    },

    // 解析地址
    parseAddressBtn(index) {
      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]
        // console.log(_that.sendAddressList[index]);
        var sendAddressItem = _that.sendAddressList[index]
        sendAddressItem.linkMan = data.name
        if (data.mobile==null || data.mobile=="" || data.mobile==undefined) {
          sendAddressItem.linkPhone = data.phone
        }else {
          sendAddressItem.linkPhone = data.mobile
        }
        sendAddressItem.sendProvince = data.province
        sendAddressItem.sendCity = data.city
        sendAddressItem.sendDistrict = data.county
        sendAddressItem.sendAddress = data.details
        // console.log(_that.sendAddressList);
        // console.log(_that.addressOption);
        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)
            }
          }
        }
        // console.log(addressOption);
        _that.addressOption[index] = addressOption
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    saveMemo() {
      const _that = this
      var data = {
        'id': _that.currentIdOrder,
        'sendMemo': _that.sendMemo
      }
      updateOrderSendMemo(data).then(res => {
        console.log(res);
        if (res.httpCode == 200) {
          _that.$message({
            message: '修改成功',
            type: 'success'
          })
        } else {
          _that.$message.error(res.msg)
        }
      })
    }
  },
  watch: {
    deliverDate() {
      this.deliverDateReal = this.deliverDate
    },
    deliverTime() {
      this.deliverTimeReal = this.deliverTime
    },
  }
}
</script>

<style lang="scss" scoped>
.textCount{
  display: inline-block;
  margin-right: 20px;
  font-size: 16px;
}
//.addressDialog {
  ::v-deep .el-dialog__body {
    padding-top: 10px;
  }

  .textShow {
    display: inline-block;
    float: right;
  }

  ::v-deep .el-card {
    margin-bottom: 10px;
  }

  .addressCard {
    ::v-deep .el-form-item {
      margin-bottom: 5px;
    }
  }

  .bottom {
    margin-top: 10px;

    ::v-deep .el-button {
      float: right;
      margin-left: 10px;
    }
  }
//}
.tabShow{
  ::v-deep .el-tabs__nav-scroll{
    height: 0;
  }
}
</style>
