<template>
  <div class="app-container" style="max-width: 1200px">
    <div class="top-right-btn" style="margin-left: 10px;margin-top: 7px">
      <el-tooltip class="item" effect="dark" content="刷新" placement="top">
        <el-button size="mini" circle icon="el-icon-refresh" @click="isEdit?editRefreshBtn():addRefreshBtn()" />
      </el-tooltip>
    </div>
    <div style="width: 70px;float: right">
      <el-button style="margin: auto" type="primary" @click="isEdit?editBtn('ruleForm'):addBtn('ruleForm')">保存</el-button>
    </div>

    <div style="clear: both"></div>

    <div class="el-page-header"
         style="padding-bottom: 10px; border-bottom: 1px solid rgb(221, 221, 221); margin-bottom: 20px;">
      <div class="el-page-header__content">{{title}}</div>
    </div>

    <el-form :model="ruleForm" label-width="130px" :rules="rules" ref="ruleForm" label-position="right">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="clientName" label="客户名称">
            <el-input v-model="ruleForm.clientName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="contactMan" label="联系人">
            <el-input v-model="ruleForm.contactMan"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="contactPhone" label="联系电话">
            <el-input v-model="ruleForm.contactPhone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="省/市/区:" class="postInfo-container-item">
            <el-cascader
              style="width: 100%"
              :options="options"
              v-model="selectedOptions1"
              @change="handleChange1">
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="address" label="详细地址">
            <el-input v-model="ruleForm.address"></el-input>
          </el-form-item>
        </el-col>
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="客户来源">-->
        <!--              <el-input v-model="ruleForm.clientFrom"></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <el-col :span="8">
          <el-form-item
            prop="overdraftQuota"
            :rules="[
                { type: 'number', message: '欠款额度必须为数字值'}
              ]"
            label="欠款额度(元)">
            <el-input v-model.number="ruleForm.overdraftQuota" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs type="border-card">
      <el-tab-pane label="收货地址">
        <div class="filter-container">
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-plus"
            size="mini"
            v-if="!addAddressFlag"
            @click="addAddressBtn()">
            增加
          </el-button>
        </div>
        <div v-show="addAddressFlag">
          <el-form
style="padding-bottom: 10px"
:label-position="labelPosition"
label-width="80px"
                   :model="formLabelAlign">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item prop="shipMode" label="发货方式">
                  <el-select v-model="formLabelAlign.shipMode" placeholder="请选择">
                    <el-option
                      v-for="item in shipModeList"
                      :key="item.id"
                      :label="item.modeName"
                      :value="item.modeName+','+item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="shipArea" label="发货区域">
                  <el-select v-model="formLabelAlign.shipArea"  placeholder="请选择">
                    <el-option
                      v-for="item in shipAreaList"
                      :key="item.id"
                      :label="item.areaName"
                      :value="item.areaName+','+item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="收货人">
                  <el-input v-model="formLabelAlign.linkManName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话">
                  <el-input v-model="formLabelAlign.linkManPhone"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="省/市/区:" class="postInfo-container-item">
                  <el-cascader
                    style="width: 100%"
                    :options="options"
                    v-model="selectedOptions"
                    @change="handleChange">
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="具体地址">
                  <el-input v-model="formLabelAlign.address"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item>
                  <el-button type="primary" @click="onSubmit">添加</el-button>
                  <el-button @click="addAddressFlag=false">取消</el-button>
                </el-form-item>
              </el-col>

            </el-row>
          </el-form>
        </div>
        <el-table border :data="gridData">
          <el-table-column width="200" v-if="this.isEdit" label="操作">
            <template slot-scope="scope">
              <!--            <el-button-->
              <!--              size="mini"-->
              <!--              @click="carAddressSelectClick(scope.$index, scope.row)">-->
              <!--              选址此地址-->
              <!--            </el-button>-->
<!--              <el-button-->
<!--                size="mini"-->
<!--                @click="carAddressEditClick(scope.$index, scope.row)">-->
<!--                修改-->
<!--              </el-button>-->
<!--              <br>-->
              <el-button
                style="margin-top: 10px"
                v-if="scope.row.defaultFlag==1"
                type="primary"
                :disabled=true
                size="mini">
                已默认
              </el-button>
              <el-button
                style="margin-top: 10px"
                v-else
                size="mini"
                @click="defaultFlagClick(scope.$index, scope.row.id)"
              >
                设置默认
              </el-button>
              <el-button
                style="margin-top: 10px"
                size="mini"
                type="danger"
                @click="carAddressDeleteClick(scope.$index, scope.row.id)">删除
              </el-button>
            </template>
          </el-table-column>
          <el-table-column property="shipModeName" label="发货方式" width="150"></el-table-column>
          <el-table-column property="shipArea" label="发货区域" width="150"></el-table-column>
          <el-table-column property="receiveMan" label="收货人" width="150"></el-table-column>
          <el-table-column property="receivePhone" label="联系电话" width="200"></el-table-column>
          <el-table-column 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 v-show="gridData.length>0" style="margin-top: 10px" class="page">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>

      </el-tab-pane>
    </el-tabs>

    <!--    <servicedialog @tableRefresh="tableRefresh" ref="menuDialog" :dialogStatus="dialogStatus" :menuId="menuId" :titleDialog="titleDialog" :dialogVisible="dialogVisible"/>-->
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
  </div>
</template>

<script>
import {
  addClientInfo,
  getIndustryInfo,
  getInfo,
  getInfoById,
  getLevelInfo,
  getPaytypeInfo,
  getshipModeListInfo,
  updateInfo,
  defaultAddress, deleteAddress,
  getshipAreaListInfo
} from '@/api/doc/client/client.js'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import Pagination from '@/components/Pagination'
import { provinceAndCityData, regionData, CodeToText, TextToCode } from 'element-china-area-data'

export default {
  components: {
    Cancledialog, Pagination
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      shipAreaList: [],
      tempRoute: {},
      selectedOptions1: [],
      selectedOptions: [],
      adrValue1: '',
      adrValue: '',
      options: regionData, // 地址地区信息
      shipModeList: [],
      total: 0,
      gridData: [],
      addAddressFlag: false,
      labelPosition: 'right',
      formLabelAlign: {
        linkManName: '',
        linkManPhone: '',
        address: '',
        idShipMode: '',
        shipModeName: '',
        shipMode: ''
      },
      title: '',
      cityshow: false,
      selected1: [], // 省市区
      selected2: [], // 省市区
      byId: '',
      dialogStatus: 1, // 1增加，2修改
      dialogTitle: '',
      dialogVisible: false,
      search: {
        keyWord: ''
      },
      ruleForm: {},
      paytypeList: [],
      industryList: [],
      levelList: [],
      rules: {
        industryName: [
          { required: true, message: '请选择行业信息', trigger: 'change' }
        ],
        levelName: [
          { required: true, message: '请选择客户等级', trigger: 'change' }
        ],
        payMode: [
          { required: true, message: '请选择付款方式', trigger: 'change' }
        ],
        clientName: [
          { required: true, message: '请填写客户名称', trigger: 'blur' }
        ],
        contactMan: [
          { required: true, message: '请填写联系人', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请填写联系电话', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请填写详细地址', trigger: 'blur' }
        ]
      },
      listData: {
        total: 0,
        page: 1,
        pageSize: 10
      },
      confirmdialog: false,
      listLoading: false,
      tableData: [],
      menuId: ''
    }
  },
  created() {
    this.getInfoData()
    // console.log(this.isEdit);
    if (this.isEdit) {
      this.title = '编辑客户信息(' + this.$route.query.clientName + ')'
      this.getClientData()

      // set page title
      this.setPageTitle()
    } else {
      this.title = '增加客户信息'
    }
    // alert("1")
    this.tempRoute = Object.assign({}, this.$route)

    this.iscityShow()
  },
  methods: {
    addRefreshBtn() {
      const _that = this
      _that.ruleForm = {}
      _that.formLabelAlign = {}
      _that.gridData = []
    },
    editRefreshBtn() {
      this.getInfoData()
      this.getClientData()
    },
    setTagsViewTitle() {
      const title = '编辑客户'

      console.log('tempRoute2', this.tempRoute)
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.$route.query.clientName}` })
      console.log('route', route)
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = '编辑客户'
      document.title = `${title}-${this.$route.query.clientName}`
    },
    getClientData() {
      const _that = this
      // console.log(_that.$route.query.id);
      // console.log(this.$route.query.clientName);
      var data = {
        idClient: _that.$route.query.id
      }
      getInfoById(data).then(res => {
        // console.log("getInfoById",res);
        var datas = res.data
        this.setTagsViewTitle()
        // console.log("getInfoById",datas);
        // var addArray = [];
        // addArray.push(datas.province);
        // addArray.push(datas.city)
        // addArray.push(datas.area)
        // _that.selectedOptions1 = addArray;

        var addressOption = []
        addressOption.push(TextToCode[datas.province].code)
        addressOption.push(TextToCode[datas.province][datas.city].code)
        addressOption.push(TextToCode[datas.province][datas.city][datas.area].code)
        // console.log(addressOption);
        // _that.addressInfo.selectedOptions = addressOption;
        _that.selectedOptions1 = addressOption

        _that.ruleForm = {
          id: _that.$route.query.id,
          idIndustry: datas.idIndustry,
          industryName: datas.industryName,
          clientName: datas.clientName,
          contactMan: datas.contactMan,
          contactPhone: datas.contactPhone,
          province: datas.province,
          city: datas.city,
          area: datas.area,
          address: datas.address,
          overdraftQuota: datas.overdraftQuota,
          idLevel: datas.idLevel,
          levelName: datas.levelName,
          idPayMode: datas.idPayMode,
          payMode: datas.payMode
        }
        _that.gridData = datas.addressList
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    onSubmit() {
      const _that = this
      // 在列表中添加地址
      if (!_that.formLabelAlign.shipMode) {
        _that.$message({
          message: '发货方式不能为空',
          type: 'warning'
        })
        return
      }
      if (!_that.formLabelAlign.shipArea) {
        _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
      }
      const data = {
        receiveMan: _that.formLabelAlign.linkManName,
        receivePhone: _that.formLabelAlign.linkManPhone,
        idShipArea: _that.formLabelAlign.shipArea.split(',')[1],
        shipArea: _that.formLabelAlign.shipArea.split(',')[0],
        idShipMode: _that.formLabelAlign.shipMode.split(',')[1],
        shipModeName: _that.formLabelAlign.shipMode.split(',')[0],
        province: _that.adrValue.split('/')[0],
        city: _that.adrValue.split('/')[1],
        area: _that.adrValue.split('/')[2],
        address: _that.formLabelAlign.address
      }
      console.log('data', data)
      _that.gridData.push(data)
      _that.formLabelAlign = {}
      _that.adrValue = ''
      _that.selectedOptions = []
    },
    // 增加
    addBtn(formName) {
      const _that = this
      console.log('adrValue1', _that.adrValue1)
      if (_that.adrValue1.length < 1) {
        _that.$message.error('请选择省市区')
        return
      }
      _that.$refs[formName].validate((valid) => {
        // console.log(valid);
        if (valid) {
          // console.log("ruleForm",_that.ruleForm);

          var dataForm = {
            idIndustry: _that.ruleForm.industryName.split(',')[1],
            industryName: _that.ruleForm.industryName.split(',')[0],
            clientName: _that.ruleForm.clientName,
            contactMan: _that.ruleForm.contactMan,
            contactPhone: _that.ruleForm.contactPhone,
            province: _that.adrValue1.split('/')[0],
            city: _that.adrValue1.split('/')[1],
            area: _that.adrValue1.split('/')[2],
            address: _that.ruleForm.address,
            overdraftQuota: _that.ruleForm.overdraftQuota * 100,
            idLevel: _that.ruleForm.levelName.split(',')[1],
            levelName: _that.ruleForm.levelName.split(',')[0],
            idPayMode: _that.ruleForm.payMode.split(',')[1],
            payMode: _that.ruleForm.payMode.split(',')[0],
            addressList: _that.gridData
          }
          console.log('dataForm', dataForm)
          var info = JSON.stringify(dataForm)
          // console.log(info);
          var data = {
            'clientInfo': info
          }

          if (_that.gridData.length < 1) {
            _that.$message.error('请添加收货地址')
            return
          }
          // console.log("clientLevel",data);
          addClientInfo(data).then(res => {
            console.log('addClientInfo', res)
            if (res.httpCode == 200) {
              _that.dialogVisible = false
              _that.$message({
                message: '增加成功,请刷新客户列表查看',
                type: 'success'
              })
              _that.$router.push({ path: '/doc/clientList' })
            } else {
              _that.$message.error(res.msg)
            }
          }).catch(err => {
            _that.$message.error(err)
            _that.dialogVisible = false
          })
        } else {
          // console.log('error submit!!');
          return false
        }
      })
    },
    getInfoData() {
      const _that = this
      if (_that.industryList.length <= 0) {
        getIndustryInfo().then(response => {
          // console.log("industryList", response.data)
          const data = response.data
          // //  组合表单数据
          _that.industryList = response.data
          // console.log(_that.shipAreaList);
        }).catch(err => {
          console.log(err)
        })
      }
      if (_that.levelList.length <= 0) {
        getLevelInfo().then(response => {
          // console.log("levelList", response.data)
          const data = response.data
          // //  组合表单数据
          _that.levelList = response.data
        }).catch(err => {
          console.log(err)
        })
      }
      // 付款方式
      if (_that.paytypeList.length <= 0) {
        getPaytypeInfo().then(response => {
          // console.log("Paytype", response.data)
          const data = response.data
          // //  组合表单数据
          _that.paytypeList = response.data
        }).catch(err => {
          console.log(err)
        })
      }
      // 发货方式
      if (_that.shipModeList.length <= 0) {
        getshipModeListInfo().then(response => {
          // console.log("shipModeList", response.data)
          const data = response.data
          // //  组合表单数据
          _that.shipModeList = response.data
        }).catch(err => {
          console.log(err)
        })
      }
      // 发货区域
      if (_that.shipAreaList.length <= 0) {
        getshipAreaListInfo().then(response => {
          console.log('shipArea', response)
          const data = response.data
          // //  组合表单数据
          _that.shipAreaList = response.data
          // console.log(_that.shipAreaList);
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 选择地区以后触发
    handleChange1(value) {
      this.adrValue1 = CodeToText[value[0]] + '/' + CodeToText[value[1]] + '/' + CodeToText[value[2]]
      console.log('adrValue1', this.adrValue1)
    },
    handleChange(value) {
      this.adrValue = CodeToText[value[0]] + '/' + CodeToText[value[1]] + '/' + CodeToText[value[2]]
      console.log('adrValue', this.adrValue)
    },
    handleCurrentChange(val) {

    },
    addAddressBtn() {
      const _that = this
      _that.addAddressFlag = true
    },
    iscityShow() {
      this.cityshow = false
      this.selected1 = []
      this.selected2 = []
      var t = setTimeout(() => {
        this.cityshow = true
      }, 0)
    },
    // 增加客户信息
    handleCreateAdd() {
      const _that = this
      _that.ruleForm = {}
      _that.dialogTitle = '增加客户'
      _that.dialogStatus = '1'
      _that.dialogVisible = true
      _that.iscityShow()
    },
    // 修改档案
    editBtn(formName) {
      const _that = this
      // console.log("编辑");
      _that.$refs[formName].validate((valid) => {
        if (_that.ruleForm.industryName.split(',').length > 1) {
          var industryName = _that.ruleForm.industryName.split(',')[0]
          var idIndustry = _that.ruleForm.industryName.split(',')[1]
        } else {
          var industryName = _that.ruleForm.industryName
          var idIndustry = _that.ruleForm.idIndustry
        }
        if (_that.ruleForm.levelName.split(',').length > 1) {
          var levelName = _that.ruleForm.levelName.split(',')[0]
          var idLevel = _that.ruleForm.levelName.split(',')[1]
        } else {
          var levelName = _that.ruleForm.levelName
          var idLevel = _that.ruleForm.idLevel
        }
        if (_that.ruleForm.payMode.split(',').length > 1) {
          var payMode = _that.ruleForm.payMode.split(',')[0]
          var idPayMode = _that.ruleForm.payMode.split(',')[1]
        } else {
          var payMode = _that.ruleForm.payMode
          var idPayMode = _that.ruleForm.idPayMode
        }
        var dataForm = {
          id: _that.$route.query.id,
          idIndustry: idIndustry,
          industryName: industryName,
          clientName: _that.ruleForm.clientName,
          contactMan: _that.ruleForm.contactMan,
          contactPhone: _that.ruleForm.contactPhone,
          province: _that.ruleForm.province,
          city: _that.ruleForm.city,
          area: _that.ruleForm.area,
          address: _that.ruleForm.address,
          overdraftQuota: _that.ruleForm.overdraftQuota,
          idLevel: idLevel,
          levelName: levelName,
          idPayMode: idPayMode,
          payMode: payMode,
          addressList: _that.gridData
        }
        // console.log("dataFormred",dataForm);
        var info = JSON.stringify(dataForm)
        var data = {
          'clientInfo': info
        }
        // console.log(data);

        updateInfo(data).then(res => {
          // console.log(res);
          if (res.httpCode == 200) {
            _that.dialogVisible = false
            _that.$message({
              message: '修改成功',
              type: 'success'
            })
            _that.$router.push({ path: '/doc/clientList' })
          } else {
            _that.$message.error(res.msg)
          }
        }).catch(err => {
          _that.$message.error(err)
          _that.dialogVisible = true
        })
      })
    },

    // 启用禁用
    editStatus(id, status) {
      var _that = this
      var data = {
        id: id,
        enable: status
      }
      var params = {
        'clientInfo': JSON.stringify(data)
      }

      var url = '/doc/enableClientInfo'
      _that.$refs.confirmDialog.updataClick(params, url)
    },
    // 刷新表格
    tableRefresh() {
      // 刷新变革
      this.getTableInfo()
    },

    // 搜索
    searchData() {
      this.listData.page = 1
      this.getTableInfo()
    },
    carEditOrderAddr(id, name) {
      this.$refs.address.outerVisible = true
      this.$refs.address.idClient = id
      this.$refs.address.clientName = name
      var pageNum = 1
      this.$refs.address.getInfo(pageNum, '')
      this.$refs.address.searchVal = ''
    },
    getAdress(adr) {
      // console.log(adr);
      // this.defaultAddress = adr;
      // // console.log(this.defaultAddress);
      // this.$forceUpdate();//重绘
    },
    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.getClientData()
          } else {
            _that.$message.error(res.msg)
          }
        }).catch(err => {
          _that.$message.error(err)
        })
      }).catch(() => {

      })
    },
    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.getClientData()
          } else {
            _that.$message.error(res.msg)
          }
        }).catch(err => {
          _that.$message.error(err)
        })
      }).catch(() => {

      })
    }
  }
}
</script>
<style>

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

  .area-select {
    height: 40px !important;
  }
</style>

<style lang="scss" scoped>
  .el-page-header__content {
    color: #409EFF;
  }

  .area-select {
    height: 40px;
  }

  .filter-container {
    margin-bottom: 15px;
  }
</style>
