<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="省份">
          <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-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>
      </el-form>
    </div>


    <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row
              style="width: 100%">
      <el-table-column align="center" label="编号" width="65">
        <template scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="名称">
        <template scope="scope">
          <span>{{scope.row.name}}</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="80" align="center" label="负责人">
        <template scope="scope">
          <span>{{scope.row.leader}}</span>
        </template>
      </el-table-column>

      <el-table-column width="200" align="center" label="负责人联系方式">
        <template scope="scope">
          <span>{{scope.row.leaderContactInfo}}</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="150">
        <template scope="scope">
          <el-button v-if="branchCompany_btn_edit" size="small" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-if="branchCompany_btn_del" size="small" type="danger" @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>


    <!--     对话框相关html元素  -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="输入名称"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model.number="form.status" placeholder="请选择状态">
            <el-option v-for="(val, key, index) in companyStatusAndCode " :key="val.code" :label="val.val"
                       :value="val.code"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属地区" prop="zoneId">
          <el-select class="filter-item" v-model="form.zoneId" placeholder="请选择">
            <el-option v-for="(val, key, index) in getAllZone()" :key="val.code" :label="val.val" :value="val.code"> </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="省份" prop="addrProvince">
          <el-select v-model.number="form.addrProvince" placeholder="请选择省份（直辖市）" >
            <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 v-model.number="form.addrCity" placeholder="请选择城市">
            <el-option v-for="item in cityRegions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="镇（县）" prop="addrTown">
          <el-select v-model.number="form.addrTown" placeholder="请选择镇（县）">
            <el-option v-for="item in townRegions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入负责人"></el-input>
        </el-form-item>

        <el-form-item label="负责人联系方式" prop="leaderContactInfo">
          <el-input v-model="form.leaderContactInfo" placeholder="请输入负责人联系方式"></el-input>
        </el-form-item>

        <el-form-item label="地址" prop="addrDetail">
          <el-input v-model="form.addrDetail" placeholder="请输入详细地址"></el-input>
        </el-form-item>

        <el-form-item label="经度" prop="longitude">
          <el-input v-model.number="form.longitude" placeholder="请输入经度"></el-input>
        </el-form-item>

        <el-form-item label="纬度" prop="latitude">
          <el-input v-model.number="form.latitude" placeholder="请输入纬度"></el-input>
        </el-form-item>

        <!--        <el-form-item >-->
<!--        <el-input value="1" v-model="form.type" disabled="true" type="hidden"></el-input>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

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

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

  import {mapGetters} from 'vuex';

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


  export default {
    name: 'branchCompany',
    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
        },
        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'
            }
          ],
          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: 20,
          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'];
    },
    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: {
      getAllZone,
      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.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;
          });
      },
      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,
          branchType: 1,
          status: undefined,
          zoneId: undefined,
          addrProvince: undefined,
          addrCity: undefined,
          addrTown: undefined,
          addrDetail: undefined,
          leader: undefined,
          longitude: undefined,
          latitude: undefined,
          leaderContactInfo: undefined,
          updateTime: undefined
        };
      }
    }
  }
</script>
