<template>
  <div>
    <div class="header-css">
      <!--@click="$router.push({name:'mypoints'})"-->
      <img @click="goBack()" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAfCAYAAADqUJ2JAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTcgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjU0OTNGQTA2QTEwNTExRTg4M0E3OUI4RkYwRDg3RUU4IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjU0OTNGQTA3QTEwNTExRTg4M0E3OUI4RkYwRDg3RUU4Ij4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6NTQ5M0ZBMDRBMTA1MTFFODgzQTc5QjhGRjBEODdFRTgiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NTQ5M0ZBMDVBMTA1MTFFODgzQTc5QjhGRjBEODdFRTgiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4bKBAsAAAAzklEQVR42qzWWQrCMBDG8VzCtVb01ZuIFJUq4nU8l+AlXEsFXz2CC+iXB2EYgjBL4P/6o4Qk0xD0q4G2aBSMyB590F2LNQkSe6OFFGmhA0PWUqSNjgxZWZEXWkqRDjpZkS46E+Sp2diIXAjyQKUUyRLIXIr0UMWQmQapGTKVInkCKaTIAF0ZMtEgN4aMNZdwR5DYRvskuH1RXEOPPfqtfgIrtFjucY5cTza9a5X1rv27uKUWc3mPXF9I+ma7YuYp4jrXXCet6+xP/o18BRgA2Nl6bmmSdvgAAAAASUVORK5CYII=" size="25" style="width: 15px; height: 20px; margin: 10px">
      <span class="header-title">{{provinceName}}分公司列表</span>
    </div>
    <div class="main-container">
      <div class="shoppings main-container">
        <div class="filter-container" ref="filter-container">
          <el-form :rules="rules4Query" ref="queryForm" style="display: flex;" :inline="inline" :model="listQuery">
            <el-select class="filter-item" style="width: 70%;margin-right: 10px;" v-model="provinceName" placeholder="请选择省份（直辖市）"  disabled="disabled">
              <el-option v-for="item in provinceRegions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select class="filter-item" v-model="listQuery.addrCity" placeholder="请选择城市"  @change='getCompanyList'>
              <el-option :key="undefined" label="全省" :value="undefined"></el-option>
              <el-option v-for="item in cityRegions4Query" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form>
        </div>
      </div>
      <!--地图-->
      <china-map :list="list" :provinceName="provinceName"></china-map>
      <!--分公司数据-->
      <div class="shoppings company-list"
           v-for="item in list"
           :key="item.key"
      >
        <div class="item-right-p company-item">
          <div class="ellipsis company-name">{{item.name}}</div>
          <p class="ellipsis">负责人：{{item.leader}}</p>
          <p>地址： {{item.address + item.addrDetail}}</p>
          <p class="ellipsis">电话：{{item.leaderContactInfo}}</p>
        </div>
      </div>
      <div class="tip-css" v-if="nodata">
        暂无数据
      </div>
      <div v-else-if="nomore" class="tip-css">
        已加载全部
      </div>
    </div>
  </div>
</template>
<style>
  .header-title {
    text-align: center;
    width: 100%;
  }
  .company-name{
    font-size: 16px;
    color: #333;
    font-weight: 600;
  }
  .company-item{
    border-bottom: 1px solid #ccc;
    padding: 5px 0;
  }
  .company-item p{
    font-size: 13px;
    color: #666;
    padding-left: 0 !important;
  }
</style>
<script>

  /*引入postcss-px2rem 通过require的形式*/
  //  var px2rem = require('postcss-px2rem');
  import {
    page,
    addObj,
    getObj,
    delObj,
    putObj
  } from 'api/base_info/branch_company';
  import chinaMap from './chinaMap';

  import {
    getSonRegionByCodes,
    getRegionByCodes,
  } from 'api/base_info/region/';

  import {mapGetters} from 'vuex';
  import BmMap from "../../../../node_modules/vue-baidu-map/components/map/Map.vue";

  export default {
    name: 'branchCompany',
    components: {
      BmMap,
      chinaMap},
    data() {
      return {
        nodata: false,
        nomore:false,
        provinceName: "",
        form: {
          id: undefined,
          name: undefined,
          status: undefined,
          addrProvince: undefined,
          addrCity: undefined,
          addrTown: undefined,
          addrDetail: undefined,
          leader: undefined,
          leaderContactInfo: undefined,
          updateTime: undefined
        },
        rules: {
          status: [
            {
              type: 'integer',
              required: true,
              message: '请输名称',
              trigger: 'blur'
            }
          ],
          name: [
            {
              required: true,
              message: '请输名称',
              trigger: 'blur'
            },
            {
              min: 0,
              max: 200,
              message: '长度小于 200 个字符',
              trigger: 'blur'
            }
          ],
          addrDetail: [
            {
              required: true,
              message: '请输入详细地址',
              trigger: 'blur'
            },
            {
              min: 0,
              max: 200,
              message: '长度小于 200 个字符',
              trigger: 'blur'
            }
          ],
          addrProvince: [
            {
              required: true,
              type: 'number',
              message: '请选择省份',
              trigger: 'blur'
            }
          ],
          addrCity: [
            {
              required: true,
              type: 'number',
              message: '请选择城市',
              trigger: 'blur'
            },
            {
              validator: (rule, value, callback) => {
                if (this.$utils.isInteger(this.form.addrProvince) &&
                  value.toString().substr(0, 2) != this.form.addrProvince.toString().substr(0, 2)) {
                  return callback(new Error('请选择省份下相应城市'));
                }
                callback();
              },
              trigger: 'blur'
            }
          ],
          addrTown: [
            {
              required: true,
              type: 'number',
              message: '请选择镇(县)',
              trigger: 'blur'
            },
            {
              validator: (rule, value, callback) => {
                if (this.$utils.isInteger(this.form.addrCity) &&
                  value.toString().substr(0, 4) != this.form.addrCity.toString().substr(0, 4)) {
                  return callback(new Error('请选择城市下相应镇（县）'));
                }
                callback();
              },
              trigger: 'blur'
            }
          ]
        },
        rules4Query: {
          addrCity: [
            {
              validator: (rule, value, callback) => {
                if (this.$utils.isUndefined(value)) {
                  return callback();
                }
                if (this.$utils.isInteger(this.listQuery.addrProvince) &&
                  value.toString().substr(0, 2) !== this.listQuery.addrProvince.toString().substr(0, 2)) {
                  return callback(new Error('请选择省份下相应城市'));
                }
                callback();
              },
              trigger: 'blur'
            }
          ]
        },
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          addrProvince: undefined,
          addrCity: undefined,
          addrTown: undefined
        },
        inline: true,
        dialogFormVisible: false,
        dialogStatus: '',
        branchCompany_btn_edit: false,
        branchCompany_btn_del: false,
        branchCompany_btn_add: false,
        textMap: {
          update: '编辑',
          create: '创建'
        },
        tableKey: 0,
        send: !1,//是否已发送请求
      }
    },
    created() {
      this.getList();
      this.branchCompany_btn_edit = this.elements['branchCompany:btn_edit'];
      this.branchCompany_btn_del = this.elements['branchCompany:btn_del'];
      this.branchCompany_btn_add = this.elements['branchCompany:btn_add'];
    },
    computed: {
      ...mapGetters([
        'elements',
        'companyStatusAndCode'
      ]),
      provinceRegions() {
        return getSonRegionByCodes(1);
      },
      cityRegions() {
        if (!this.$utils.isInteger(this.form.addrProvince)) {
          return null;
        }
        return getSonRegionByCodes(this.form.addrProvince);
      },
      townRegions() {
        if (!this.$utils.isInteger(this.form.addrCity)) {
          return null;
        }
        return getSonRegionByCodes(this.form.addrCity);
      },
      cityRegions4Query() {
        if (!this.$utils.isInteger(this.listQuery.addrProvince)) {
          return null;
        }
        return getSonRegionByCodes(this.listQuery.addrProvince);
      },
      townRegions4Query() {
        if (!this.$utils.isInteger(this.listQuery.addrCity)) {
          return null;
        }
        return getSonRegionByCodes(this.listQuery.addrCity);
      }
    },
    methods: {
      //返回按钮
      goBack() {
        let that = this;
        this.$router.push({path: '/companyInfo'});
      },
      getCompanyList(e){
        this.getList();
      },
      getValue(e){
        if(!e){
          //全国
          location.reload();
//          this.provinceName = "china";
          return;
        }
        this.provinceName = e;
        this.listQuery.addrCity = undefined;
//        this.getList();
      },
      headCall: function (msg) { //回调方法，接收子组件传的参数
        this.listQuery.addrProvince = msg;
        this.getList();
      },
      getStatusName(code) {
        if (!this.$utils.isInteger(code)) {
          return '未知';
        }
        return this.companyStatusAndCode[code].val;
      },
      getList(reachBottom) {
        if(this.send){
          return;
        }
        if(!reachBottom){
          this.list = [];
          this.listQuery.page = 1;
          this.nodata = false;
          this.nomore = false;
        } else if(reachBottom) {
          if(this.nomore){
            return false
          }
        }
        this.send = !0;
        page(this.listQuery)
          .then(response => {
            let listTemp = response.data.data;
            //一次读入所有涉及地区，防止多次读取
            if (!this.$utils.isEmpty(listTemp)) {
              let allRegions = new Set();
              for (let index in listTemp) {
                allRegions.add(listTemp[index].addrProvince);
                allRegions.add(listTemp[index].addrCity);
                allRegions.add(listTemp[index].addrTown);
                let regions = getRegionByCodes([listTemp[index].addrProvince, listTemp[index].addrCity, listTemp[index].addrTown]);
                listTemp[index].address = regions[0].name + ' ' + regions[1].name + ' ' + regions[2].name + ' ';
              }
              getRegionByCodes([...allRegions]);
            }
            let arr = this.list;
//            if(this.listQuery.page >1){
            listTemp.map(function(item){
              arr.push(item);
            });
//            }
            this.list = arr;
            this.total = response.data.totalCount;
            this.listLoading = false;
            if(arr.length == this.listQuery.page*this.listQuery.limit){
              this.listQuery.page++;
            }else if(arr.length == 0){
              this.nodata = true;
            }else if(arr.length < this.listQuery.page*this.listQuery.limit){
              this.nomore = true;
            }
            this.send = !1;
          })
      },
      getAddrStr(branchCompany) {
        let regions = getRegionByCodes([branchCompany.addrProvince, branchCompany.addrCity, branchCompany.addrTown]);
        return regions[0].name + ' ' + regions[1].name + ' ' + regions[2].name + ' ';
      },
      handleFilter() {
        this.$refs.queryForm.validate(valid => {

          if (valid) {
            this.getList();
          } else {
            return false;
          }
        });
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      handleCreate() {
        this.resetTemp();
        this.dialogStatus = 'create';
        this.dialogFormVisible = true;
      },
      handleUpdate(row) {
        getObj(row.id)
          .then(response => {
            this.form = response.data;
            this.dialogFormVisible = true;
            this.dialogStatus = 'update';
            this.selectedProvince = response.data.addrProvince;
            this.selectedCity = response.data.addrCity;
          });
      },
      scroll() {
        let isLoading = false
        window.onscroll = () => {
          // 距离底部20px时加载一次
          let bottomOfWindow = document.documentElement.offsetHeight - document.documentElement.scrollTop - window.innerHeight <= 0;
          if (bottomOfWindow && isLoading == false) {
            this.getList(true);
            setTimeout(function(){
              isLoading = true;
            });
          }
        }
      },
      handleDelete(row) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            delObj(row.id)
              .then(() => {
                this.$notify({
                  title: '成功',
                  message: '删除成功',
                  type: 'success',
                  duration: 2000
                });
                const index = this.list.indexOf(row);
                this.list.splice(index, 1);
              });
          });
      },
      create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            addObj(this.form)
              .then(() => {
                this.dialogFormVisible = false;
                this.getList();
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                });
              })
          } else {
            return false;
          }
        });
      },
      cancel(formName) {
        this.dialogFormVisible = false;
        this.$refs[formName].resetFields();
      },
      update(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            this.dialogFormVisible = false;
            putObj(this.form).then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              });
            });
          } else {
            return false;
          }
        });
      },
      resetTemp() {
        this.form = {
          id: undefined,
          name: undefined,
          status: undefined,
          addrProvince: undefined,
          addrCity: undefined,
          addrTown: undefined,
          addrDetail: undefined,
          leader: undefined,
          leaderContactInfo: undefined,
          updateTime: undefined
        };
      }
    },
    mounted() {    // 滚动加载更多 
      debugger
      this.listQuery.addrProvince = this.$route.query.provinceId;
      this.provinceName = this.$route.query.provinceName;
      this.$nextTick(() => {
        window.addEventListener('scroll', this.scroll)
      })
    },
  }
</script>
