<template>
  <div class="address">
    <!--        <area-select type='text' :level='2' v-model="selected" :data="pcaa"></area-select>-->

    <el-dialog :title="clientName+'收货地址信息'" :append-to-body="append" width="1040px" :visible.sync="outerVisible">
      <div class="address-search">
        <el-input placeholder="地址关键字" v-model="searchVal" class="input-with-select">
          <el-button @click="handleSearch" slot="append" type="success" icon="el-icon-search">搜索</el-button>
        </el-input>
      </div>
      <div class="address-tit">
        <el-button type="primary" @click="addAddress">新增地址</el-button>
      </div>
      <div style="clear: both;margin-bottom: 20px"></div>

      <el-dialog
        width="600px"
        :title="title"
        :visible.sync="innerVisible"
        append-to-body>
        <el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign">
          <el-form-item label="智能识别">
            <el-input type="textarea" size="mini" :rows="4" style="width: 400px" placeholder="粘贴地址" v-model="parseAddress" clearable></el-input>
            <el-button size="mini" type="green" @click="parseAddressBtn()">识别</el-button>
          </el-form-item>
          <el-form-item prop="shipMode" label="发货方式">
            <el-select v-model="formLabelAlign.shipMode" filterable  placeholder="请选择">
<!--              <el-option-->
<!--                v-for="item in shipModeList"-->
<!--                :key="item.id"-->
<!--                :label="item.modeName"-->
<!--                :value="item.modeName+','+item.id">-->
<!--              </el-option>-->
              <template  v-if="!sendType || sendType == undefined" >
                <el-option
                  v-for="item in sendKinds"
                  :key="item.id"
                  :label="item.modeName"
                  :value="item.id">
                </el-option></template>
              <template v-else>
                <el-option
                  v-for="item in sendKinds"
                  :key="item.id"
                  :label="item.logisticName"
                  :value="item.id">
                </el-option>
              </template>
            </el-select>
            <el-checkbox style="width: 60px" v-model="sendType" @change="chooseLogistics(sendType)">物流</el-checkbox>
          </el-form-item>
          <el-form-item label="收货人">
            <el-input v-model="formLabelAlign.linkManName"></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="formLabelAlign.linkManPhone"></el-input>
          </el-form-item>
          <el-form-item label="选择地区">
            <el-form-item label="" class="postInfo-container-item">
              <el-cascader
                style="width: 100%"
                filterable
                :options="options"
                v-model="selectedOptions"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-form-item>
          <el-form-item label="具体地址">
            <el-input v-model="formLabelAlign.address"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">关闭</el-button>
          <el-button type="primary" @click="addAddressSure()">确定</el-button>
        </div>
      </el-dialog>
      <el-table border :data="gridData">
        <el-table-column width="260" label="操作">
          <template slot-scope="scope">
            <template v-if="!isChoose">
              <!--            <el-button-->
              <!--              size="mini"-->
              <!--              @click="carAddressSelectClick(scope.$index, scope.row)">-->
              <!--              选址此地址-->
              <!--            </el-button>-->
              <el-button
                style="display: inline-block"
                size="mini"
                @click="carAddressEditClick(scope.$index, scope.row)">
                修改
              </el-button>
              <el-button
                style="display: inline-block"
                v-if="scope.row.defaultFlag==1"
                type="primary"
                :disabled=true
                size="mini">
                已默认
              </el-button>
              <el-button
                style=""
                v-else
                size="mini"
                @click="defaultFlagClick(scope.$index, scope.row.id)"
              >
                设置默认
              </el-button>
              <el-button
                style="display: inline-block"
                size="mini"
                type="danger"
                @click="carAddressDeleteClick(scope.$index, scope.row.id)">删除
              </el-button>
            </template>
            <template v-else>
              <el-button @click="chooseThis(scope.row)" type="primary" size="mini">
                选择
              </el-button>
              <el-button
                style="display: inline-block"
                v-if="scope.row.defaultFlag==1"
                type="primary"
                :disabled=true
                size="mini">
                已默认
              </el-button>
              <el-button
                style=""
                v-else
                size="mini"
                @click="defaultFlagClick(scope.$index, scope.row.id)"
              >
                设置默认
              </el-button>
            </template>
          </template>
        </el-table-column>
        <el-table-column property="shipModeName" label="发货方式" width="100"></el-table-column>
        <el-table-column property="receiveMan" label="收货人" width="80"></el-table-column>
        <el-table-column property="receivePhone" label="联系电话" width="120"></el-table-column>
        <el-table-column show-overflow-tooltip property="address" label="地址">
          <template slot-scope="scope">
            <div>
              {{ scope.row.province }}{{ scope.row.city }}{{ scope.row.area }}{{ scope.row.address }}
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
      <div style="clear: both"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="outerVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import 'vue-area-linkage/dist/index.css'
import {pca, pcaa} from 'area-data'
import {provinceAndCityData, regionData, CodeToText, TextToCode} from 'element-china-area-data'
import {
  getAddressInfo,
  addAddressInfo,
  updateAddressInfo,
  getshipModeListInfo,
  defaultAddress,
  deleteAddress
} from '@/api/doc/client/client.js'
import {getLogisticsInfoList, parseAddress} from "@/api/order/orderDetail";
export default {
  name: 'Addressdny',
  props: {
    isChoose: {
      type: Boolean,
      default: false
    },
    append: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      parseAddress: '',
      rowData:{},
      sendKinds: [],
      sendType:false,
      adrValue: '',
      selectedOptions: [],
      options: regionData, // 地址地区信息
      clientName: '',
      shipModeList: [],
      index: '',
      pca: pca,
      pcaa: pcaa,
      outerVisible: false,
      innerVisible: false,
      idClient: '',
      gridData: [],
      total: 0,
      searchVal: '',
      selected: [],
      title: '',
      addressid: '',
      type: 0, // type=1 新增地址, type = 2 修改地址
      cityshow: false,
      labelPosition: 'right',
      formLabelAlign: {
        linkManName: '',
        linkManPhone: '',
        address: '',
        idShipMode: '',
        shipModeName: '',
        shipMode: '',
        shipOrLogistics:""
      }
    }
  },
  mounted() {
  },
  methods: {
    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]
        _that.$set(_that.formLabelAlign,'linkManName',data.name);
        if (data.mobile) {
          _that.$set(_that.formLabelAlign,'linkManPhone',data.mobile);
        }
        if (data.phone) {
          _that.$set(_that.formLabelAlign,'linkManPhone',data.phone);
        }
        _that.adrValue = data.province + "/" + data.city + "/" + data.county;
        _that.$set(_that.formLabelAlign,'address',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.selectedOptions = addressOption;
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 选择物流档案
    chooseLogistics(sendType) {
      // console.log(row);
      const _that = this
      if (sendType) {
        _that.getLogisticsInfo()
      } else {
        _that.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)
      })
    },
    handleChange(value) {

      this.adrValue = CodeToText[value[0]] + '/' + CodeToText[value[1]] + '/' + CodeToText[value[2]]
      // console.log('adrValue', this.adrValue)
    },
    carAddressDeleteClick(index, id) {
      const _that = this
      _that.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        var data = {
          'idReceiveAddress': id
        }

        deleteAddress(data).then(res => {
          // console.log(res);
          if (res.httpCode == 200) {
            _that.$message({
              message: '删除成功',
              type: 'success'
            })
            _that.getInfo(1, '')
          } else {
            _that.$message.error(res.msg)
          }
        }).catch(err => {
          _that.$message.error(err)
        })
      }).catch(() => {

      })
    },
    defaultFlagClick(index, id) {
      const _that = this
      _that.$confirm('设置默认？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        var data = {
          'idReceiveAddress': id
        }

        defaultAddress(data).then(res => {
          // console.log(res);
          if (res.httpCode == 200) {
            _that.$message({
              message: '设置成功',
              type: 'success'
            })
            _that.getInfo(1, '')
          } else {
            _that.$message.error(res.msg)
          }
        }).catch(err => {
          _that.$message.error(err)
        })
      }).catch(() => {

      })
    },
    iscityShow() {
      this.cityshow = false
      this.selected = []
      var t = setTimeout(() => {
        this.cityshow = true
      }, 0)
    },
    carAddressEditClick(index, order) {
      const _that = this
      _that.iscityShow()
      // console.log(index);
      // console.log('order', order)
      _that.type = 2;
      if(order.shipOrLogistics==1){
        _that.sendType = true
      }else {
        _that.sendType = false
      }
      _that.chooseLogistics(_that.sendType);
      _that.innerVisible = true
      _that.title = '修改客户地址'
      var addressOption = []
      if(order.province){
        addressOption.push(TextToCode[order.province].code)
        addressOption.push(TextToCode[order.province][order.city].code)
        addressOption.push(TextToCode[order.province][order.city][order.area].code)
      }

      // console.log(addressOption);
      // _that.addressInfo.selectedOptions = addressOption;
      _that.selectedOptions = addressOption
      _that.adrValue = order.province + "/" + order.city + "/" + order.area;
      _that.formLabelAlign.linkManName = order.receiveMan
      _that.formLabelAlign.linkManPhone = order.receivePhone
      _that.formLabelAlign.address = order.address
      _that.formLabelAlign.idShipMode = order.idShipMode
      _that.formLabelAlign.shipModeName = order.shipModeName
      _that.formLabelAlign.shipMode = order.idShipMode,
      _that.addressid = order.id,
      _that.formLabelAlign.shipOrLogistics = order.shipOrLogistics
    },
    addAddressSure() {
      const _that = this
      // console.log(_that.formLabelAlign.shipMode);
      if (!_that.formLabelAlign.shipMode) {
        _that.$message({
          message: '发货方式不能为空',
          type: 'warning'
        })
        return
      }
      if (!_that.formLabelAlign.linkManName) {
        _that.$message({
          message: '收货人不能为空',
          type: 'warning'
        })
        return
      }
      if (!_that.formLabelAlign.linkManPhone) {
        _that.$message({
          message: '联系电话不能为空',
          type: 'warning'
        })
        return
      }
      if (_that.adrValue.length <= 0) {
        _that.$message({
          message: '省市区不能为空',
          type: 'warning'
        })
        return
      }
      if (!_that.formLabelAlign.address) {
        _that.$message({
          message: '具体地址不能为空',
          type: 'warning'
        })
        return
      }
      if (_that.type == 1) {
        var shipModeName = "";
        if(_that.sendType){
          shipModeName =_that.sendKinds.find(x=> x.id === _that.formLabelAlign.shipMode).logisticName;
          var shipOrLogistics = 1;
        }else {
          shipModeName =_that.sendKinds.find(x=> x.id === _that.formLabelAlign.shipMode).modeName;
          var shipOrLogistics = 0;
        }
        const data = {
          idClient: _that.idClient,
          receiveMan: _that.formLabelAlign.linkManName,
          receivePhone: _that.formLabelAlign.linkManPhone,
          idShipMode: _that.formLabelAlign.shipMode,
          shipModeName:shipModeName,
          province: _that.adrValue.split('/')[0],
          city: _that.adrValue.split('/')[1],
          area: _that.adrValue.split('/')[2],
          address: _that.formLabelAlign.address,
          shipOrLogistics: shipOrLogistics
        }
        // console.log(data);
        // return
        var infoData = JSON.stringify(data)
        var info = {
          'receiveAddress': infoData
        }

        addAddressInfo(info).then(res => {
          // console.log(res);
          if (res.httpCode == 200) {
            _that.innerVisible = false
            _that.$message({
              message: '增加成功',
              type: 'success'
            })
            _that.getInfo(1, '')
          } else {
            _that.innerVisible = false
            _that.$message.error(res.msg)
          }
        }).catch(err => {
          _that.$message.error(err)
          _that.innerVisible = false
        })
      } else {
        var shipModeName = "";
        // console.log(_that.sendKinds);
        // console.log(_that.formLabelAlign.shipMode);
        if(_that.sendType){
          shipModeName =_that.sendKinds.find(x=> x.id === _that.formLabelAlign.shipMode).logisticName;
          var shipOrLogistics = 1;
        }else {
          shipModeName =_that.sendKinds.find(x=> x.id === _that.formLabelAlign.shipMode).modeName;
          var shipOrLogistics = 0;
        }

        const data = {
          id: _that.addressid,
          receiveMan: _that.formLabelAlign.linkManName,
          receivePhone: _that.formLabelAlign.linkManPhone,
          idShipMode: _that.formLabelAlign.shipMode,
          shipModeName: shipModeName,
          province: _that.adrValue.split('/')[0],
          city: _that.adrValue.split('/')[1],
          area: _that.adrValue.split('/')[2],
          address: _that.formLabelAlign.address,
          shipOrLogistics:shipOrLogistics
        }
        var infoData = JSON.stringify(data)
        var info = {
          'receiveAddress': infoData
        }
        updateAddressInfo(info).then(res => {
          // console.log(res);
          if (res.httpCode == 200) {
            _that.innerVisible = false
            _that.$message({
              message: '修改成功',
              type: 'success'
            })
            _that.getInfo(1, '')
          } else {
            _that.innerVisible = false
            _that.$message.error(res.msg)
          }
        }).catch(err => {
          _that.$message.error(err)
          _that.innerVisible = false
        })
      }
    },

    addAddress() {
      const _that = this
      _that.type = 1
      _that.innerVisible = true
      _that.title = '增加地址'
      _that.adrValue = '';
      _that.parseAddress="";
      _that.selectedOptions = [];
      _that.formLabelAlign = {};
      _that.sendType = false;
      _that.chooseLogistics(_that.sendType);
      _that.iscityShow()
    },
    getInfo(pageNum, keyWord) {
      const _that = this
      var params = {
        idClient: _that.idClient
      }
      var page = {
        pageSize: 10,
        pageIndex: pageNum
      }

      var dataInfo = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page)
      }

      getAddressInfo(dataInfo).then(response => {
        // console.log("getAddressInfo", response.data)
        // //  组合表单数据
        _that.gridData = response.data
        // _that.industryList = response.data;
        // console.log(_that.shipAreaList);
      }).catch(err => {
        console.log(err)
      })

      // // 发货方式
      // if (_that.shipModeList.length <= 0) {
      //   getshipModeListInfo().then(response => {
      //     // console.log("shipModeList", response.data)
      //     _that.shipModeList = response.data;
      //     // console.log(err)
      //   })
      // }
    },
    handleCurrentChange(val) {
      this.getInfo(val, '')
    },
    handleSearch() {
      // 搜索收货地址
      const _that = this
      if (!_that.searchVal) {
        _that.$message({
          message: '地址关键字不能为空',
          type: 'warning'
        })
        return
      }
      _that.getInfo(1, _that.searchVal)
    },

    // 弹窗内选择操作
    chooseThis(row) {
      console.log('点击选择');
      this.$emit('chooseAddress', row)
    }
  }
}
</script>

<style scoped>
.page {
  float: right;
  margin-top: 20px;
}

.address-search {
  display: inline-block;
  width: 270px;
  float: left;
}

.address-tit {
  display: inline-block;
  float: left;
  margin-left: 15px;
}

.area-select .area-selected-trigger {
  padding: 0px 20px 0px 12px !important;
}

</style>
