<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" ref="filter-container">
      <el-form :rules="rules4Query" ref="queryForm" :inline="inline" :model="listQuery">
        <el-form-item label="所属地区" prop="zoneId">
          <el-select class="filter-item" v-model="listQuery.zoneId" placeholder="请选择" @change="getProvinceRegions">
            <el-option :key="undefined" label="无" :value="undefined"></el-option>
            <el-option v-for="val in getAllZoneList" :key="val.id" :label="val.name" :value="val.id"> </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="片区" prop="addrCity">-->
        <!--<el-select class="filter-item" v-model="listQuery.addrCity" placeholder="请选择片区">-->
        <!--<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-item>-->
        <el-form-item label="省份">
          <el-select class="filter-item" v-model="listQuery.addrProvince" placeholder="请选择省份（直辖市）"  @change='getValue'>
            <el-option :key="undefined" label="无" :value="undefined"></el-option>
            <el-option v-for="item in provinceRegions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="addrCity">
          <el-select class="filter-item" v-model="listQuery.addrCity" placeholder="请选择城市">
            <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-item>
        <el-form-item label="简称">
          <el-input v-model="listQuery.name" placeholder="请输入公司简称"></el-input>
        </el-form-item>
        <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
        <el-button class="filter-item" v-if="branchCompany_btn_add" style="margin-left: 10px;" @click="handleCreate"
                   type="primary" icon="edit">添加
        </el-button>
        <!--<form methods="post" enctype="multipart/form-data" style="display:inline-block;margin-left:10px;;">-->
          <!--<el-button class="filter-item" type="primary" v-waves @click="choiceImg">导入</el-button>-->
          <!--<input ref="filElem" type="file" name="file" class="upload-file" @change="getFile($event)" style="display:none;">-->
        <!--</form>-->
      </el-form>
    </div>


    <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row
              style="width: 100%">
      <el-table-column
        type="index"
        align="center" label="序号" width="65">
      </el-table-column>
      <el-table-column align="center" label="公司全称">
        <template scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="公司简称">
        <template scope="scope">
          <span>{{scope.row.companyName}}</span>
        </template>
      </el-table-column>

      <el-table-column width="80" align="center" label="状态">
        <template scope="scope">
          <span>{{getStatusName(scope.row.status)}}</span>
        </template>
      </el-table-column>
      <el-table-column width="180" align="center" label="股价">
        <template scope="scope">
          <span>{{scope.row.price?scope.row.price/10000:0}}{{scope.row.type == 1?'万/股':'港万/股'}}</span>
        </template>
      </el-table-column>

      <el-table-column width="180" align="center" label="负责人">
        <template scope="scope">
          <span>{{scope.row.leader}}</span>
        </template>
      </el-table-column>

      <el-table-column width="150" align="center" label="负责人联系方式">
        <template scope="scope">
          <span>{{scope.row.leaderContactInfo}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column width="150" align="center" label="租车客服电话">-->
        <!--<template scope="scope">-->
          <!--<span>{{scope.row.vehiceServicePhone}}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <!--<el-table-column width="150" align="center" label="旅游客服电话">-->
        <!--<template scope="scope">-->
          <!--<span>{{scope.row.tourServicePhone}}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <!--<el-table-column width="300" align="center" label="地址">-->
        <!--<template scope="scope">-->
          <!--<span>{{getAddrStr(scope.row) + scope.row.addrDetail}}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->

      <!--<el-table-column width="150" align="center" label="经度">-->
        <!--<template scope="scope">-->
          <!--<span>{{scope.row.longitude}}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->

      <!--<el-table-column width="150" align="center" label="纬度">-->
        <!--<template scope="scope">-->
          <!--<span>{{scope.row.latitude}}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->

      <!--<el-table-column width="180" align="center" label="最后更新时间">-->
        <!--<template scope="scope">-->
          <!--<span>{{scope.row.updateTime?scope.row.updateTime:scope.row.createTime}}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->

      <el-table-column align="center" label="操作" width="300" fixed="right">
        <template scope="scope">
          <el-button size="small"  class="el-button el-button--text el-button--small"  @click="handleView(scope.row)">详情</el-button>
          <el-button size="small"  class="el-button el-button--text el-button--small"  @click="handleSetting(scope.row)">基础信息</el-button>
          <el-button v-if="branchCompany_btn_edit" size="small"  class="el-button el-button--text el-button--small"  @click="handleCompanyInfo(scope.row)">公司介绍</el-button>
          <el-button size="small"  class="el-button el-button--text el-button--small"  @click="handleSettingStock(scope.row)" v-if="compnay_stock_update">设置股权</el-button>
          <el-button v-if="branchCompany_btn_del" size="small"  class="el-button el-button--text el-button--small"  style="color: red;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>

    <!--公司介绍设置弹框-->
    <companyInfoModal v-if="companyInfoVisible" :row="row" :dialogStatus = "dialogStatus" :title="textMap[dialogStatus]"  v-on:companyInfoDialogEvent = "companyInfoDialogEvent"></companyInfoModal>
    <!--股权设置-->
    <stockRightModal v-if="stockRightVisible" :row="row" v-on:stockRightDialogEvent = "stockRightDialogEvent"></stockRightModal>
    <!--查看详情-->
    <info v-if="infoVisible" :row="row" v-on:infoDialogEvent = "infoDialogEvent"></info>
  </div>
</template>
<style>
  .el-dialog__footer{
    border-top: 1px solid #bfcbd9;
  }
</style>

<script>
  import axios from 'axios';
  import {
    page,
    addObj,
    getObj,
    deleteOne,
    putObj
  } from 'api/base_info/branch_company';

  import {
    getSysRegionByIds
  } from 'api/vehicle/vehicleInfo/';

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

  import {mapGetters} from 'vuex';

  import {
    getAllZone
  } from 'api/base_info/constant/';

  import companyInfoModal from "./companyInfoModal"
  import stockRightModal from "./stockRightModal"
  import info from "./info"
  export default {
    name: 'branchCompany',
    components: {
      companyInfoModal,
      stockRightModal,
      info
    },
    data() {
      return {
        form: {
          id: undefined,
          name: undefined,
          branchType: 1,
          status: undefined,
          zoneId: undefined,
          addrProvince: undefined,
          addrCity: undefined,
          addrTown: undefined,
          addrDetail: undefined,
          leader: undefined,
          longitude: undefined,
          latitude: undefined,
          leaderContactInfo: undefined,
          updateTime: undefined,
          vehiceServicePhone: undefined,
          tourServicePhone: undefined
        },
        companyInfoVisible: false,//公司介绍-弹框
        stockRightVisible: false,//设置股权
        infoVisible: false,//详情弹框
        allZoneArr:[],//全部片区
        provinceRegions: [],//片区下省份数据
          compnay_stock_update:false,
        rules: {
          latitude: [
            {
              type: 'number',
              required: false,
              message: '请输入数字',
              trigger: 'blur'
            }
          ],
          longitude: [
            {
              type: 'number',
              required: false,
              message: '请输入数字',
              trigger: 'blur'
            }
          ],
          status: [
            {
              type: 'integer',
              required: true,
              message: '请输名称',
              trigger: 'blur'
            }
          ],
          zoneId: [
            {
              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'
            }
          ],
          leaderContactInfo: [
            {
              required: true,
              message: '请输入联系人电话',
              trigger: 'blur'
            },
            {
              validator: (rule, value, callback) => {
                if (!value) {
                  return callback(new Error('手机号不能为空'));
                } else {
                  const reg = /^[1](([3][0-9])|([4][5,7,9])|([5][0-9])|([6][6])|([7][1,2,3,5,6,7,8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/
                  console.log(reg.test(value));
                  if (reg.test(value)) {
                    callback();
                  } else {
                    return callback(new Error('请输入正确的手机号'));
                  }
                }
              },
              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'
            }
          ]
        },
        row: {},//编辑弹框参数
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          name: undefined,//简称
          zoneId: undefined,
          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,
      }
    },
    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'];
      this.compnay_stock_update = this.elements['compnay:stock:update']
    },
    computed: {
      ...mapGetters([
        'elements',
        'companyStatusAndCode'
      ]),
      getAllZoneList(){
        this.allZoneArr = getAllZone();
        return getAllZone();
      },
      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: {
      /**
       * 查看详情
       * */
      handleView(row){
        this.row = {
          id: row.id,
          companyId: row.companyId,
          stockId: row.stockId
        };
        this.infoVisible = true;
      },
      /**
       * 基础信息
       * */
      handleSetting(row){
        this.dialogStatus = 'infoUpdate';
        this.row = {
          id: row.id,
          companyId: row.companyId
        }
        this.companyInfoVisible = true;//基础信息弹框
      },
      /**
       * 设置股权
       * */
      handleSettingStock(row){
        this.row = {
          stockId: row.stockId,
          id: row.id,
        };
        this.stockRightVisible = true;
      },
      /**
       * 公司介绍
       * */
      handleCompanyInfo(row){
        this.dialogStatus = 'companyInfoUpdate';
        this.row = {
          id: row.id,
          companyId: row.companyId
        };
        this.companyInfoVisible = true;//公司介绍弹框
      },
      /**
       * 关闭公司介绍弹框
       * */
      companyInfoDialogEvent(e){
        this.companyInfoVisible = false;//公司介绍弹框
        if(e){
          this.getList();
        }
      },
      /**
       * 关闭股权设置弹框
       * */
      stockRightDialogEvent(e){
        this.stockRightVisible = false;//股权设置弹框
        if(e){
          this.getList();
        }
      },
      /**
       * 查看详情-关闭
       * */
      infoDialogEvent(){
        this.infoVisible = false;
      },

      /**
       * 根据片区获取省份数据
       * */
      getProvinceRegions() {
        let that = this;
        this.listQuery.addrCity = undefined;
        this.listQuery.addrProvince = undefined;
        if (!this.$utils.isInteger(this.listQuery.zoneId)) {
          return null;
        }
        this.allZoneArr.map(function(item){
          if(item.id == that.listQuery.zoneId){
            getSysRegionByIds(item.provinceIds).then(response => {
              let listRs = undefined;
              if (!that.$utils.isEmpty(response.data)) {
                listRs = response.data;
              }
              that.provinceRegions = listRs;
            });
          }
        });
      },

      getValue(e){
        this.listQuery.addrCity = undefined;
      },

      getStatusName(code) {
        if (!this.$utils.isInteger(code)) {
          return '未知';
        }
        return this.companyStatusAndCode[code].val;
      },
      /**
       * 获取分公司列表
       * */
      getList() {
        this.listLoading = true;
        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);
              }
              getRegionByCodes([...allRegions]);
            }
            this.list = listTemp;
            this.total = response.data.totalCount;
            this.listLoading = false;
          })
      },
      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.companyInfoVisible = true;//公司介绍弹框
      },
      handleUpdate(row) {
        var that = this;
        getObj(row.id)
          .then(response => {
            this.allZoneArr.map(function(item){
              if(item.id == response.data.zoneId){
                getSysRegionByIds(item.provinceIds).then(res => {
                  let listRs = undefined;
                  if (!that.$utils.isEmpty(res.data)) {
                    listRs = res.data;
                  }
                  that.provinceRegions = listRs;
                });
              }
            });
            this.form = response.data;
            this.dialogFormVisible = true;
            this.dialogStatus = 'update';
            this.selectedProvince = response.data.addrProvince;
            this.selectedCity = response.data.addrCity;
          });
      },
      /**
       * 删除
       * */
      handleDelete(row) {
        let t = this;
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
          let params = {id: row.id};
            deleteOne(params)
              .then((res) => {
                if(res.status==200){
                  this.$notify({
                    title: '成功',
                    message: '删除成功',
                    type: 'success',
                    duration: 2000
                  });
                  t.getList();
                } else {
                  this.$notify({
                    title: '失败',
                    message: res.message,
                    type: 'error',
                    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(res => {
                if(res.status==200){
                   this.dialogFormVisible = false;
                  this.getList();
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  });
                }else{
                   this.$notify({
                    title: '失败',
                    message: res.message,
                    type: 'error',
                    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) {
            putObj(this.form).then(res => {
              if(res.status==200){
                   this.dialogFormVisible = false;
                  this.getList();
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  });
                }else{
                   this.$notify({
                    title: '失败',
                    message: res.message,
                    type: 'error',
                    duration: 2000
                  });
                }
            });
          } else {
            return false;
          }
        });
      },
      choiceImg(){
        this.$refs.filElem.dispatchEvent(new MouseEvent('click'))
      },
      getFile(event){
        let formData = new FormData();
        formData.append('file',event.target.files[0]);
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        axios.post('/vehicle/branchCompany/importExcel', formData, config).then(function (res) {
          if (res.status === 2000) {
            /*这里做处理*/
          }
        })
      },
      resetTemp() {
        this.form = {
          id: undefined,
          name: undefined,
          branchType: 1,
          status: undefined,
          zoneId: undefined,
          addrProvince: undefined,
          addrCity: undefined,
          addrTown: undefined,
          addrDetail: undefined,
          leader: undefined,
          longitude: undefined,
          latitude: undefined,
          leaderContactInfo: undefined,
          updateTime: undefined,
          vehiceServicePhone: undefined,
          tourServicePhone: undefined
        };
      }
    }
  }
</script>
