<template>
  <div class="app-container">
    <addressdny @getAdress="getAdress" ref="address"></addressdny>
    <div class="filter-container">

      <el-input v-model="search.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>

      <el-button
        v-if="!isChoose"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="$router.push({path:'/doc/createCustomer'})">
        增加客户
      </el-button>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getTableInfo" />
        </el-tooltip>
      </div>
    </div>
    <el-table
      :data="tableData"
      v-loading="listLoading"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      default-expand-all>
      <el-table-column label="操作" align="center" width="270" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <template v-if="!isChoose">
          <el-button @click="$router.push({path:'/doc/editCustomer/'+row.id,query:{id:row.id,clientName:row.clientName}})" type="primary" size="mini">
            编辑
          </el-button>
          <el-button @click="editStatus(row.id,'0')" type="danger" v-if="row.enable==1" size="mini">
            禁用
          </el-button>
          <el-button @click="editStatus(row.id,'1')" v-else="row.enable==0" size="mini">
            启用
          </el-button>
<!--          <el-button size="mini" @click="carEditOrderAddr(row.id,row.clientName)" type="primary">配置收货地址</el-button><br>-->
          </template>
          <template v-else>
            <el-button @click="chooseThis(row)" type="primary" size="mini">
              选择
            </el-button>
          </template>

        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag v-if="row.enable==1" type="success">
            启用
          </el-tag>
          <el-tag v-else="row.enable==0" type="danger">
            禁用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="clientName"
        label="客户名称">
      </el-table-column>
      <el-table-column
        prop="industryName"
        label="所属行业">
      </el-table-column>
      <el-table-column
        prop="levelName"
        label="客户级别">
      </el-table-column>
      <el-table-column
        prop="payMode"
        label="付款方式">
      </el-table-column>
      <el-table-column
        prop="contactMan"
        label="联系人">
      </el-table-column>
      <el-table-column
        width="150"
        prop="contactPhone"
        label="联系电话">
      </el-table-column>
      <el-table-column
        align="left"
        class-name="status-col"
        width="280"
        label="联系地址">
        <template slot-scope="{row}">
          <span>{{row.province+row.city+row.area+row.address}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="left"
        class-name="status-col"
        width="280"
        label="欠款额度(元)">
        <template slot-scope="{row}">
          <span>{{row.overdraftQuota*0.01}}</span>
        </template>
      </el-table-column>

    </el-table>
    <pagination
v-show="listData.total>0"
:total="listData.total"
:page.sync="listData.page"
                :limit.sync="listData.pageSize"
@pagination="getTableInfo"/>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px">

      <el-form :model="ruleForm" label-width="130px" :rules="rules" ref="ruleForm" label-position="right">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="industryName" label="行业信息">
              <el-select v-model="ruleForm.industryName" placeholder="请选择">
                <el-option
                  v-for="item in industryList"
                  :key="item.id"
                  :label="item.industryName"
                  :value="item.industryName+','+item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="levelName" label="客户等级">
              <el-select v-model="ruleForm.levelName" placeholder="请选择">
                <el-option
                  v-for="item in levelList"
                  :key="item.id"
                  :label="item.levelName"
                  :value="item.levelName+','+item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="payMode" label="付款方式">
              <el-select v-model="ruleForm.payMode" placeholder="请选择">
                <el-option
                  v-for="item in paytypeList"
                  :key="item.id"
                  :label="item.payMode"
                  :value="item.payMode+','+item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="clientName" label="客户名称">
              <el-input v-model="ruleForm.clientName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="contactMan" label="联系人">
              <el-input v-model="ruleForm.contactMan"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="contactPhone" label="联系电话">
              <el-input v-model="ruleForm.contactPhone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省市区">
              <area-cascader :data="pcaa" :level="1" type="text" placeholder="请选择地区" v-if="cityshow" v-model='selected'></area-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <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="12">
            <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-col :span="12">-->
          <!--            <el-form-item label="所属业务员">-->
          <!--              <el-input v-model="ruleForm.salesManNameBelong"></el-input>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='1'?addBtn('ruleForm'):editBtn('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!--    <servicedialog @tableRefresh="tableRefresh" ref="menuDialog" :dialogStatus="dialogStatus" :menuId="menuId" :titleDialog="titleDialog" :dialogVisible="dialogVisible"/>-->
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
  </div>
</template>

<script>
import {
  addInfo,
  getIndustryInfo,
  getInfo,
  getInfoById,
  getLevelInfo,
  getPaytypeInfo,
  updateInfo
} from '@/api/doc/client/client.js'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import Pagination from '@/components/Pagination'
import Addressdny from '@/components/Dialog/Addressdny.vue'
import 'vue-area-linkage/dist/index.css'
import { pca, pcaa } from 'area-data'

export default {
  name: 'ClientList',
  components: {
    Cancledialog, Pagination, Addressdny
  },
  props: {
    isChoose: {
      type: Boolean,
      default: false
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      cityshow: false,
      selected: [], // 省市区
      pca: pca,
      pcaa: pcaa,
      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: ''
    }
  },
  mounted() {
    this.getTableInfo()
  },
  methods: {
    iscityShow() {
      this.cityshow = false
      this.selected = []
      var t = setTimeout(() => { this.cityshow = true }, 0)
    },
    // 获取列表
    getTableInfo() {
      const _that = this
      _that.listLoading = true
      var params = _that.search
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      if (_that.search.keyWord) {
        var data = {
          'params': JSON.stringify(params),
          'page': JSON.stringify(page)
        }
      } else {
        var data = {
          'params': {},
          'page': JSON.stringify(page)
        }
      }

      // console.log(data);
      getInfo(data).then(response => {
        // console.log("tableData",response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        _that.listData.total = response.total
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.listLoading = false
      })
      if (_that.industryList.length <= 0) {
        getIndustryInfo(data).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(data).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)
        })
      }
    },
    // 增加客户信息
    handleCreateAdd() {
      const _that = this
      _that.ruleForm = {}
      _that.dialogTitle = '增加客户'
      _that.dialogStatus = '1'
      _that.dialogVisible = true
      _that.iscityShow()
    },
    // 增加
    addBtn(formName) {
      const _that = this
      console.log('_that.ruleForm', _that.ruleForm)
      if (_that.selected.length < 1) {
        _that.$message.error('请选择省市区')
      }
      _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.selected[0],
            city: _that.selected[1],
            area: _that.selected[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]
          }
          // console.log("dataForm", dataForm);
          var info = JSON.stringify(dataForm)
          // console.log(info);
          var data = {
            'clientInfo': info
          }

          // console.log("clientLevel",data);
          addInfo(data).then(res => {
            // console.log(res);
            if (res.httpCode == 200) {
              _that.dialogVisible = false
              _that.$message({
                message: '增加成功',
                type: 'success'
              })
              _that.tableRefresh()
            } else {
              _that.$message.error(res.msg)
            }
          }).catch(err => {
            _that.$message.error(err)
            _that.dialogVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 唤起修改
    handleUpdate(id) {
      const _that = this
      _that.dialogTitle = '修改客户信息'
      _that.dialogVisible = true
      _that.dialogStatus = '2'
      _that.byId = id
      _that.iscityShow()
      var data = {
        idClient: id
      }

      getInfoById(data).then(res => {
        // console.log(res);
        var datas = res.data
        // console.log("getInfoById",datas);
        var addArray = []
        addArray.push(datas.province)
        addArray.push(datas.city)
        addArray.push(datas.area)
        _that.selected = addArray

        _that.ruleForm = {
          id: 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
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 修改档案
    editBtn(formName) {
      const _that = this
      _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.byId,
          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
        }
        // 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.tableRefresh()
          } 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();//重绘
    },

    // 弹窗内选择操作
    chooseThis(row) {
      // console.log('点击选择');
      this.$emit('chooseClient', row)
    }
  }
}
</script>
<style>
  .area-select .area-selected-trigger {
    padding: 0px 20px 7px 12px !important;
  }

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

<style lang="scss" scoped>
  .area-select {
    height: 40px;
  }

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