<template>
  <div class="app-container" style="max-width: 1200px">
    <div style="width: 70px;float: right">

    </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 style="display: inline-block" class="el-page-header__content">
        {{ title }}
        <el-button  size="mini" style="margin-left: 7px;display: inline-block" type="primary" @click="isEdit?editBtn('ruleForm'):addBtn('ruleForm')">保存
        </el-button>
      </div>

    </div>

    <el-form :model="ruleForm" label-width="130px" :rules="rules" ref="ruleForm" label-position="right">
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item prop="clientName" label="客户名称">
            <el-input v-model.trim="ruleForm.clientName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="contactMan" label="联系人">
            <el-input v-model.trim="ruleForm.contactMan"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="contactPhone" label="联系电话">
            <el-input v-model.trim="ruleForm.contactPhone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <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="14">
          <el-form-item label="具体地址">
            <el-input v-model="ruleForm.address"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
  </div>
</template>

<script>
import {
  addClientInfo,
  getInfoById,
  updateInfo
} 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 {
      parseCustomer:"",
      parseAddress: '',
      sendType:false,
      shipAreaList: [],
      tempRoute: {},
      selectedOptions1: [],
      selectedOptions: [],
      adrValue1: '',
      adrValue: '',
      options: regionData, // 地址地区信息
      addAddressFlag: false,
      labelPosition: 'right',
      title: '',
      cityshow: false,
      selected1: [], // 省市区
      selected2: [], // 省市区
      byId: '',
      dialogStatus: 1, // 1增加，2修改
      dialogTitle: '',
      dialogVisible: false,
      search: {
        keyWord: ''
      },
      ruleForm: {},
      rules: {
        clientName: [
          {required: true, message: '请填写客户名称', trigger: 'blur'}
        ],
        contactMan: [
          {required: true, message: '请填写联系人', trigger: 'blur'}
        ],
        contactPhone: [
          {required: true, message: '请填写联系电话', trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请填写详细地址', trigger: 'blur'}
        ]
      },
      confirmdialog: false,
      listLoading: false,
      menuId: ''
    }
  },
  created() {
    // 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: {
    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
      var data = {
        idClient: _that.$route.query.id
      }
      getInfoById(data).then(res => {
        // console.log("getInfoById",res);

        var datas = res.data
        this.setTagsViewTitle()
        var addressOption = [];
        if(datas.province){
          addressOption.push(TextToCode[datas.province].code)
          addressOption.push(TextToCode[datas.province][datas.city].code)
          addressOption.push(TextToCode[datas.province][datas.city][datas.area].code)
        }
        _that.selectedOptions = addressOption

        _that.ruleForm = {
          id: _that.$route.query.id,
          clientName: datas.clientName,
          contactMan: datas.contactMan,
          contactPhone: datas.contactPhone,
          province: datas.province,
          city: datas.city,
          area: datas.area,
          address: datas.address
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 增加
    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 = {
            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
          }
          // console.log('dataForm', dataForm)
          var info = JSON.stringify(dataForm)
          // console.log(info);
          var data = {
            'clientInfo': info
          }
          // 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.$store.dispatch("tagsView/delView", _that.$route);
              _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
        }
      })
    },
    handleChange(value) {
      const _that = this
      _that.adrValue = CodeToText[value[0]] + '/' + CodeToText[value[1]] + '/' + CodeToText[value[2]]
      _that.ruleForm.province = CodeToText[value[0]]
      _that.ruleForm.city = CodeToText[value[1]]
      _that.ruleForm.area = 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)
    },
    // 修改档案
    editBtn(formName) {
      const _that = this
      // console.log("编辑");
      _that.$refs[formName].validate((valid) => {
        var dataForm = {
          id: _that.$route.query.id,
          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
        }
        // 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.$store.dispatch("tagsView/delView", _that.$route);
            _that.$router.push({path: '/doc/clientList'})

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