<template>
  <div class="app-container">
    <div class="createPost-main-container">
      <div class="filter-container" v-if="!isRead">
        <el-row :gutter="20">
          <el-col :span="2" :offset="22">
            <el-button
              class="filter-item"
              type="success"
              @click="isEdit?editSaveClient('form'):saveClient('form')">
              保存
            </el-button>
          </el-col>
        </el-row>

      </div>
      <el-form label-width="90px" :model="form" :rules="rules" ref="form">
        <el-row>
          <el-col :span="16">
            <el-form-item label="客户名称:" prop="clientName" class="postInfo-container-item">
              <el-input v-model="form.clientName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人:" class="postInfo-container-item">
              <el-input v-model="form.leader"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="绑定手机:" prop="mobilePhone" class="postInfo-container-item">
              <el-input v-model="form.mobilePhone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出货顺序:" class="postInfo-container-item">
              <el-select v-model="form.sendPriority" filterable placeholder="请选择">
                <el-option
                  v-for="item in sendPrioritys"
                  :key="item.id"
                  :label="item.tagName"
                  :value="item.tagName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务员:" class="postInfo-container-item">
              <el-input v-model="form.saleMan"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户级别:" prop="clientLevel" class="postInfo-container-item">
              <el-select v-model="form.clientLevel" filterable placeholder="请选择">
                <el-option
                  v-for="item in clientLevels"
                  :key="item.id"
                  :label="item.levelName"
                  :value="item.levelName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款方式:" class="postInfo-container-item">
              <el-select v-model="form.payKind" filterable placeholder="请选择">
                <el-option
                  v-for="item in payWays"
                  :key="item.id"
                  :label="item.tagName"
                  :value="item.tagName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="企业规模:" class="postInfo-container-item">
              <el-input v-model="form.clientSize"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="开票信息:" class="postInfo-container-item">
              <el-input v-model="form.billState"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="平台对应ID:" class="postInfo-container-item">
              <el-input v-model="form.bankNo2"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注:" class="postInfo-container-item">
          <el-input type="textarea" :rows="2" v-model="form.remark"></el-input>
        </el-form-item>
        <el-tabs type="border-card" style="max-width: 1200px">
          <el-tab-pane label="收货地址">
            <div v-if="addAddressFlag">
              <el-form size="mini" :model="addressInfo" :rules="addressRule" ref="addressInfo" label-width="90px">
                <el-row>
                  <el-col :span="16">
                    <el-form-item label="地址别名" prop="otherName">
                      <el-input style="width: 200px" v-model="addressInfo.otherName"></el-input>
                      <span style="color: rgba(7,8,10,0.73); margin-left: 10px">例如：家/公司/门店/工厂等等</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="送货方式:" prop="sendKind" class="postInfo-container-item">
                      <el-select v-model="addressInfo.sendKind" filterable placeholder="请选择">
                        <el-option
                          v-for="item in sendKinds"
                          :key="item.id"
                          :label="item.tagName"
                          :value="item.tagName">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="物流快递:" class="postInfo-container-item">
                      <el-input v-model="addressInfo.logistics"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="邮政编码:" class="postInfo-container-item">
                      <el-input v-model="addressInfo.postCode"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="地址信息:" prop="selectedOptions" class="postInfo-container-item">
                      <el-cascader
                        style="width: 90%"
                        size="mini"
                        :options="options"
                        v-model="addressInfo.selectedOptions"
                        @change="handleChange">
                      </el-cascader>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="收货人姓名:" label-width="100px" prop="consignee" class="postInfo-container-item">
                      <el-input v-model="addressInfo.consignee"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="详细地址:" prop="addressTagName" class="postInfo-container-item">
                      <el-input
style="width: 90%"
v-model="addressInfo.addressTagName"
type="textarea"
                                :row="2"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="收货人电话:" label-width="100px" prop="phone" class="postInfo-container-item">
                      <el-input v-model="addressInfo.phone"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item>
                  <el-button type="primary" @click="addressType==1?saveAddress('addressInfo'):editAddress('addressInfo')">保存</el-button>
                  <el-button  @click="addAddressFlag = false">取消</el-button>
                </el-form-item>
              </el-form>
            </div>
            <hr v-if="addAddressFlag"/>
            <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>
            <el-table
              :data="form.clientAddressInfo"
              v-loading="listLoading"
              style="width: 100%;margin-bottom: 20px;"
              row-key="id"
              border
              size="mini"
              default-expand-all>
              <el-table-column
                prop="otherName"
                label="地址别名">
              </el-table-column>
              <el-table-column
                label="收货人"
                prop="consignee"
              >
              </el-table-column>
              <el-table-column
                prop="addressArea"
                label="所在地区">
              </el-table-column>
              <el-table-column
                prop="addressTagName"
                label="详细地址">
              </el-table-column>

              <el-table-column
                prop="sendKind"
                label="送货方式">
              </el-table-column>
              <el-table-column
                prop="phone"
                label="电话">
              </el-table-column>
              <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button @click="updateAddressBtn(scope)" type="primary" size="mini">
                    编辑
                  </el-button>
                  <el-button @click="setdefaultFlag(scope)" type="danger" v-if="scope.row.defaultFlag==0" size="mini">
                    设置为默认地址
                  </el-button>
                  <el-button v-else="scope.row.defaultFlag==1" size="mini">
                    默认地址
                  </el-button>

                </template>
              </el-table-column>

            </el-table>
          </el-tab-pane>
          <el-tab-pane label="QQ">
            <el-button type="success" @click='addRow'>添加</el-button>
            <!--            <el-button type="danger" @click="deleteRow">删除</el-button>-->
            <!--            <el-button type="primary" @click='saveQdCode'>保存</el-button>-->

            <el-table tooltip-effect="dark" ref="clientQQInfo" stripe :data="form.clientQQInfo">
              <el-table-column label="QQ号" width="150">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.status" v-model="scope.row.cilentQQ"/>
                  <span v-else>{{scope.row.cilentQQ}}</span>
                </template>
              </el-table-column>
              <el-table-column label="QQ昵称" width="150">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.status" v-model="scope.row.cilentQQName"/>
                  <span v-else>{{scope.row.cilentQQName}}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button v-if="!scope.row.status" @click="editRow(scope)" type="primary" size="mini">
                    编辑
                  </el-button>
                  <el-button v-else @click="saveRow(scope)" type="success" size="mini">
                    保存
                  </el-button>
                  <el-button @click="deleteRow(scope)" type="danger" size="mini">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
  </div>
</template>

<script>
import { verifyPhoneNum, addClientInfo, getParameter, getClientLevelList, getClientInfoByID, updateClientInfo } from '@/api/baseInfo/client/addClient.js'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import Pagination from '@/components/Pagination'
import { provinceAndCityData, regionData, CodeToText, TextToCode } from 'element-china-area-data'

const addressInfo = {
  otherName: '', // 地址别名
  sendKind: '', // 送货方式
  idLogistics: '', // 物流快递id
  logistics: '', // 物流快递：
  addressArea: '', // 地址区域信息：
  addressTagName: '', // 详细地址：
  // addressCoordinates: '',//地址坐标：
  postCode: '', // 邮政编码：
  consignee: '', // 收货人姓名：
  phone: '', // 联系电话：
  defaultFlag: '', // 设置是否为默认地址：
  selectedOptions: []
}
const form = {
  clientName: '', // 客户名称,
  leader: '', // 负责人
  mobilePhone: '', // 绑定手机
  clientLevel: '', // 客户级别
  sendPriority: '', // 出货顺序
  clientSize: '', // 企业规模
  billState: '', // 开票信息
  payKind: '', // 付款方式
  idSaleMan: '', // 业务员id
  saleMan: '', // 业务员
  bankNo2: '', // 平台对应ID
  clientAddressInfo: [], // 收货信息
  clientQQInfo: [], // QQ信息
  remark: ''// 备注说明,
}
export default {
  components: {
    Cancledialog, Pagination
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    isRead: {
      type: Boolean,
      default: false
    }
  },
  // filters: {
  //   statusFilter(status) {
  //     const statusMap = {
  //       1: 'success',
  //       0: 'danger'
  //     }
  //     return statusMap[status]
  //   }
  // },
  data() {
    // 检查手机号是否注册过
    var checkClientPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号'))
      } else if (!this.isCellPhone(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的手机号!'))
      } else {
        if (this.isEdit) {
          callback()
        } else {
          setTimeout(() => {
            verifyPhoneNum({ 'phoneNum': value }).then(res => {
              // console.log(res);
              if (res.httpCode == 200) {
                callback()
              } else {
                callback(new Error('此号码已绑定'))
              }
            }).catch(err => {
              callback(new Error('此号码已绑定'))
            })
          }, 1000)
        }
      }
    }
    // 检查手机格式
    var checkphone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号'))
      } else if (!this.isCellPhone(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    }
    return {
      dialogStatus: 1, // 1增加，2修改
      dialogTitle: '',
      dialogVisible: false,
      listLoading: false,
      form: Object.assign({}, form),
      addressInfo: Object.assign({}, addressInfo),
      addAddressFlag: false, // 添加收货地址标记
      options: regionData, // 地址地区信息
      parameterInfo: [], // 选择参数
      sendPrioritys: [], // 出货顺序
      payWays: [], // 付款方式
      sendKinds: [], // 送货方式
      clientLevels: [], // 客户级别
      addressType: 1, // 1为添加收货信息，2为修改收货地址
      editAddressIndex: '', // 修改收货地址的index值
      rules: {
        clientName: [
          { required: true, message: '请输入客户名称' }
        ],
        mobilePhone: [
          { validator: checkClientPhone, required: true, trigger: 'blur' }
        ],
        clientLevel: [
          { required: true, message: '请选择客户级别', trigger: 'change' }
        ]
      },
      addressRule: {

        otherName: [
          { required: true, message: '请输入地址别名' }
        ],
        sendKind: [
          { type: 'string', required: true, message: '请输入送货方式', trigger: 'change' }
        ],
        selectedOptions: [
          { required: true, message: '请输入地址信息' }
        ],
        addressTagName: [
          { required: true, message: '请输入详细地址' }
        ],
        consignee: [
          { required: true, message: '请输入收货人姓名' }
        ],
        phone: [
          { validator: checkphone, required: true, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    var clientId = this.$route.query.id
    // console.log(clientId);
    if (this.isEdit) {
      this.getClientInfo(clientId)
    }
    if (this.isRead) {
      this.getClientInfo(clientId)
    }
  },
  mounted() {
    this.getParameterInfo('')
    this.getClientLevel()
  },
  methods: {
    // 获取客户信息
    getClientInfo(id) {
      var _that = this
      var idPrint = id
      var data = {
        id: idPrint
      }

      getClientInfoByID(data).then(res => {
        console.log(res)
        const data = res.data
        _that.form = {
          id: data.id,
          clientName: data.clientName, // 客户名称,
          leader: data.leader, // 负责人
          mobilePhone: data.mobilePhone, // 绑定手机
          clientLevel: data.clientLevel, // 客户级别
          sendPriority: data.sendPriority, // 出货顺序
          clientSize: data.clientSize, // 企业规模
          billState: data.billState, // 开票信息
          payKind: data.payKind, // 付款方式
          idSaleMan: data.idSaleMan, // 业务员id
          saleMan: data.saleMan, // 业务员
          bankNo2: data.bankNo2, // 平台对应ID
          clientAddressInfo: data.clientAddressInfo, // 收货信息
          clientQQInfo: data.clientQQInfo, // QQ信息
          remark: data.remark// 备注说明,
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 选择地区以后触发
    handleChange(value) {
      this.addressInfo.addressArea = CodeToText[value[0]] + '/' + CodeToText[value[1]] + '/' + CodeToText[value[2]]
    },

    // 增加收货地址
    addAddressBtn() {
      var _that = this
      _that.addressType = 1
      _that.addAddressFlag = true
      _that.addressInfo = Object.assign({}, addressInfo)
    },

    // 编辑收货地址
    updateAddressBtn(scope) {
      console.log(scope)
      var _that = this
      _that.addressType = 2
      _that.addAddressFlag = true
      _that.addressInfo = scope.row
      _that.editAddressIndex = scope.$index
      var address = scope.row.addressArea.split('/')
      var addressOption = []
      addressOption.push(TextToCode[address[0]].code)
      addressOption.push(TextToCode[address[0]][address[1]].code)
      addressOption.push(TextToCode[address[0]][address[1]][address[2]].code)
      // console.log(addressOption);
      _that.addressInfo.selectedOptions = addressOption
    },
    setdefaultFlag(scope) {
      var _that = this
      _that.form.clientAddressInfo.forEach((item, index) => {
        if (scope.$index == index) {
          item.defaultFlag = 1
        } else {
          item.defaultFlag = 0
        }
      })
    },

    // 检查手机号
    isCellPhone(val) {
      if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    },

    // 保存收货地址
    saveAddress(formName) {
      var _that = this
      _that.$refs[formName].validate((valid) => {
        if (valid) {
          delete _that.addressInfo.selectedOptions
          _that.addAddressFlag = false
          _that.form.clientAddressInfo.push(_that.addressInfo)
        }
      })
    },
    // 修改收获地址
    editAddress(formName) {
      var _that = this
      _that.$refs[formName].validate((valid) => {
        if (valid) {
          delete _that.addressInfo.selectedOptions
          _that.addAddressFlag = false
          _that.form.clientAddressInfo.forEach((item, index) => {
            if (index == _that.editAddressIndex) {
              item = _that.addressInfo
            }
          })
        }
      })
    },
    // 添加行
    addRow() {
      this.form.clientQQInfo.map(item => {
        if (item.status) {
          item.status = 0
        }
        return item
      })
      var list = {
        cilentQQ: '',
        cilentQQName: '',
        status: '1'
      }
      this.form.clientQQInfo.push(list)
    },
    // 编辑行
    editRow(scope) {
      this.form.clientQQInfo.forEach((item, index) => {
        if (scope.$index == index) {
          item.status = 1
        }
      })
    },
    // 保存行
    saveRow(scope) {
      this.form.clientQQInfo.forEach((item, index) => {
        if (scope.$index == index) {
          item.status = 0
        }
      })
    },
    // 删除行
    deleteRow(scope) {
      this.form.clientQQInfo.splice(scope.$index, 1)
    },

    // 保存客户档案
    saveClient(formName) {
      var _that = this
      _that.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(_that.form)
          var info = JSON.stringify(_that.form)
          var data = {
            'info': info
          }
          // console.log(data);
          // return

          addClientInfo(data).then(res => {
            // console.log(res);
            if (res.httpCode == 200) {
              _that.$message({
                message: '增加成功',
                type: 'success'
              })
              _that.$router.push({ path: '/baseInfo/clientInfo' })
            } else {
              _that.$message.error(res.msg)
            }
          }).catch(err => {
            _that.$message.error(err)
          })
        }
      })
    },
    closeSelectedTag(view) {
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
        if (this.isActive(view)) {
          this.toLastView(visitedViews, view)
        }
      })
    },
    // 修改客户档案
    editSaveClient(formName) {
      var _that = this
      _that.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(_that.form)
          var info = JSON.stringify(_that.form)
          var data = {
            'info': info
          }

          // console.log(data);
          // return;
          updateClientInfo(data).then(res => {
            // console.log(res);
            if (res.httpCode == 200) {
              _that.closeSelectedTag()
              _that.$message({
                message: '修改成功',
                type: 'success'
              })
              _that.$router.push({ path: '/baseInfo/clientInfo' })
            } else {
              _that.$message.error(res.msg)
            }
          }).catch(err => {
            _that.$message.error(err)
          })
        }
      })
    },

    // 选择参数获取
    getParameterInfo(type) {
      var _that = this
      // console.log(data);
      // return
      var params = {
        'groupName': type
      }
      // console.log(params);
      var data = {
        'params': JSON.stringify(params)
      }

      getParameter(data).then(res => {
        console.log(res)
        if (res.httpCode == 200) {
          _that.parameterInfo = res.data
          _that.parameterInfo.forEach((item) => {
            if (item.groupName == '付款方式') {
              _that.payWays = item.children
            } else if (item.groupName == '出货顺序') {
              _that.sendPrioritys = item.children
            } else if (item.groupName == '发货方式') {
              _that.sendKinds = item.children
            }
          })
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 获取客户级别
    getClientLevel() {
      var _that = this
      var data = {}

      getClientLevelList(data).then(res => {
        console.log(res)
        if (res.httpCode == 200) {
          _that.clientLevels = res.data
          // _that.parameterInfo.forEach((item) => {
          //   if(item.groupName == '付款方式'){
          //     _that.payWays = item.children
          //   }
          // })
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>

  @import "~@/styles/mixin.scss";

  .filter-container {
    margin-bottom: 15px;
  }

  .createPost-main-container {
    max-width: 1200px;
    padding: 10px 35px 20px 40px;
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }

</style>
