<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item>
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新 增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="loading" :data="addressList">
        <el-table-column label="序号" prop="id" align="center"></el-table-column>
        <el-table-column label="售后地址" prop="address" align="center">
          <template slot-scope="scope">
            <div style="width:80%;margin:0 auto; text-align: center;">
              {{scope.row.address}}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="联系人" prop="contact_person" align="center"></el-table-column>
        <el-table-column label="联系电话" prop="contact_phone" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.limit"
        @pagination="getList"
      />
    </el-card>
    <!-- 新增、修改 -->
    <el-dialog :title="addTitle" :visible.sync="isOpen" width="50%">
      <el-form v-if="isOpen" :model="addressForm" :rules="addressRules" ref="addressForm" label-width="100px">
        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="联系人：" prop="contact_person">
              <el-input v-model="addressForm.contact_person"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="联系电话：" prop="contact_phone">
              <el-input v-model="addressForm.contact_phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="省市区：" prop="address_ids">
              <el-cascader v-model="areaList" :props='props' @change="handleChanges" placeholder="请选择具体的省市区" style="width:100%"></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="详细地址：" prop="address">
              <el-input v-model="addressForm.address"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="save('addressForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getAddressList, getAreaList, addAddress, getAddressDetails, deleteAddress} from '@/api/module/retreat/address';

  export default {
    name: "Address",
    data() {
      // 省市区三级地址校验
      let areaCheck = (rule, value, callback) => {
        if(this.addressForm.address_ids.length === 0) {
          callback(new Error('省市区三级地址不能为空'));
        }else {
          callback();
        }
      };
      // 手机号码格式校验
      let checkTel = (rule, value, callback) => {
        const reg = /^1[3456789]\d{9}$/;
        if(!reg.test(value)){
          callback(new Error('手机号码格式有误'));
        }else {
          callback();
        }
      };
      return {
        fullHeight: '',
        tableHeight: 500,
        areaList: [], // 省市区
        props: {
          expandTrigger: 'click',
          lazy: true,
          lazyLoad: this.lazyLoad,
          value: "id",
          label: 'name',
          leaf: 'leaf'
        },
        isOpen: false,
        loading: false,
        total: 0,
        // 查询参数
        queryParams:{
          page: 1,
          limit: 10,
        },
        // 售后地址列表
        addressList:[],
        addTitle: '新增/修改', // 新增，修改  弹窗名
        // 新增、修改表单
        addressForm: {
          id: 0,
          contact_person: '',
          contact_phone: '',
          address_ids: [],
          address: ''
        },
        // 新增修改表单验证
        addressRules: {
          contact_person :[{ required: true, message: '联系人不能为空', trigger: 'blur' }],
          contact_phone :[
            {required: true, message: '联系人手机号码不能为空', trigger: 'blur'},
            {required: true, validator: checkTel,trigger: 'blur' }
            ],
          address_ids :[{ required: true, message: '', validator: areaCheck }],
          address :[{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
        }
      }
    },
    created() {
      this.getList();
      this.$nextTick(() => {
        this.fullHeight = document.getElementsByClassName('box-card')[0].clientHeight;
      })
    },

    watch: {
      fullHeight(val) {
        let formHeight = document.getElementsByClassName('clearfix')[0].clientHeight
        this.tableHeight = val - formHeight - 110
      }
    },
    methods: {
      // 获取列表
      getList() {
        this.loading = true;
        getAddressList(this.queryParams).then(res => {
          if(res.code === 1 && res.data.data) {
            this.addressList = res.data.data;
            this.total = res.data.count;
            this.loading = false;
          }
        });
      },

      //
      lazyLoad(node, resolve) {
        this.getArea(node, resolve);
      },
      //
      getArea(node, resolve) {
        const level = node.level;
        let limboNode = {};
        if(level === 0) {
          limboNode = {pid: 0}
        }
        if(level === 1) {
          limboNode = { pid: node.value };
        }
        if(level === 2) {
          limboNode = { pid: node.value };
        }

        getAreaList(limboNode).then(res => {
          let result = {};
          if (level === 0) {
            result = res.data
            result.forEach(item => {
              item.value = item.id;
              item.label = item.name;
              item.children=[];
              item.leaf = 0;  // 可以控制 是否有下级   值为true都不行，必须等于0
            })
          }

          if (level === 1) {
            result = res.data
            result.forEach(item => {
              item.value = item.id;
              item.label = item.name
              item.children=[];
              //这句代码表示当点击最后一级的时候 label后面不会转圈圈 并把相关值赋值到选择器上
              item.leaf = 0
            })
          }

          if (level === 2) {
            result = res.data
            result.forEach(item => {
              item.value = item.id;
              item.label = item.name
              item.leaf = 1;
            })
          }
          resolve(result)
        });
      },
      // 新增
      handleAdd() {
        this.isOpen = true;
        this.addTitle = "新增地址";
        this.areaList = [];
        this.resetForm('addressForm');

        console.log(230,this.addressForm);
      },

      handleDelete(row) {
        const roleIds = row.id || this.ids;
        this.$confirm('是否确认删除编号为"' + roleIds + '"的数据项？', '确认信息', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          return deleteAddress(roleIds);
        }).then(()=> {
          this.getList();
          this.msgSuccess('删除成功')
        }).catch(action => {});
      },

      // 修改
      handleUpdate(row) {
        this.isOpen = true;
        this.areaList = [];
        const roleIds = row.id || this.ids;
        //this.loading = true;
        getAddressDetails(roleIds).then(res => {
          if(res && res.data) {
            // 处理 三级联动回显
            let areaListAry = res.data.address_ids.split(",");
            for(let i = 0; i < areaListAry.length; i++) {
              this.areaList.push(Number(areaListAry[i]));
            }
            this.addressForm = res.data;
          }
        });
      },
      cancel() {
        this.areaList = [];
        this.resetForm('addressForm');
        this.isOpen = false;

      },
      save(form) {
        if(typeof this.addressForm.address_ids === "string") {
          let areaListAry = this.addressForm.address_ids.split(",");
          let areaList = [];
          for(let i = 0; i < areaListAry.length; i++) {
            areaList.push(Number(areaListAry[i]));
          }
          this.addressForm.address_ids = areaList;
        }

        this.$refs[form].validate((valid) => {
          if(valid) {
            addAddress(this.addressForm).then(res => {
              if(res.code && res.code === 1) {
                if(this.addressForm.id === 0) {
                  this.$message({ message: '新增成功', type: 'success'});
                }else {
                  this.$message({ message: '修改成功', type: 'success'});
                }

                this.getList();
              }else if( res.code === 0){
                if(res.msg) {
                  this.$message({ message: res.msg, type: 'error'});
                }else {
                  this.$message({ message: '新增失败', type: 'error'});
                }
              }
              this.resetForm('addressForm');
              this.isOpen = false;
            });
          }
        });
      },
      //
      handleChanges(value) {
        //this.areaList = value;
        this.addressForm.address_ids = value;
      },
      // 查询
      handleQuery() {

      },
      // 重置
      resetQuery() {

      },

    }
  }
</script>

<style lang="scss" type="text/stylus" scoped>
  .app-container {
    height: 100%;
  }

  .box-card {
    height: 100%;
  }

  .box-card /deep/ .el-card__body {
    height: 100%;
    overflow: hidden;
  }
  .el-table {
    height: calc(100% - 137px);
    overflow: scroll;
  }
</style>
