<template>
  <div class="divBox">
    <el-card class="box-card">
      <!--顶部搜索-->
      <div slot="header" class="clearfix">
        <div class="container">
          <el-form size="small" label-width="100px" :inline="true">
            <el-form-item label="提货点名称：" label-width="100px" style="display: inline-block;">
              <el-input style="width: 350px" v-model="tableFrom.mer_take_name" placeholder="请输入提货点名称" class="selWidth" clearable></el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-button size="small" type="primary" @click="getList(1)">搜索</el-button>
        <el-button size="small" type="success" @click="diaLogChangeStatus()">添加提货点</el-button>
      </div>
      <!--列表-->
      <el-table v-loading="listLoading" :data="tableData.data">
        <el-table-column prop="id" label="ID" min-width="80" align="center"/>
        <el-table-column label="名称" prop="mer_take_name" min-width="150" align="center"/>
        <el-table-column label="手机号" prop="mer_take_phone" min-width="150" align="center"/>
        <el-table-column label="详细地址" prop="mer_take_address" min-width="150" align="center"/>
        <el-table-column label="添加时间" prop="create_time" min-width="150" align="center"/>
        <el-table-column label="操作" min-width="280" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="success" size="small" @click="editInfo(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteDel(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <div class="block">
        <el-pagination
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <!--提货点编辑弹框-->
    <el-dialog :title="Number(info.id) > 0 ? '编辑提货点' : '添加提货点'" :visible.sync="pointShow" width="80%" :before-close="diaLogChangeStatus">
      <el-card class="box-card">
        <el-form ref="editInfoField" :model="info" :rules="rules" label-width="150px">
          <el-form-item label="提货点名称：" prop="mer_take_name">
            <el-input v-model="info.mer_take_name" placeholder="请输入详细地址" />
          </el-form-item>
          <el-form-item label="提货点电话：" prop="mer_take_phone">
            <el-input v-model="info.mer_take_phone" placeholder="请输入提货点电话" />
          </el-form-item>
          <el-form-item label="经纬度：" prop="mer_take_location">
            <el-input :value="Object.values(info.mer_take_location).toString()" enter-button="查找位置" placeholder="请查找位置" readonly>
              <el-button slot="append" type="primary" @click="onSearchs">查找位置</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="详细地址：" prop="mer_take_address">
            <el-input v-model="info.mer_take_address" placeholder="请输入详细地址" />
          </el-form-item>
          <el-form-item label="提货点营业日期：" prop="mer_take_day">
            <el-select v-model="info.mer_take_day" filterable multiple placeholder="请选择营业时间" class="mer-take-day">
              <el-option v-for="item in date" :key="item.date_id" :label="item.date_name" :value="item.date_id" />
            </el-select>
          </el-form-item>
          <el-form-item label="提货点营业时间：" prop="mer_take_time" required>
            <el-time-picker v-model="info.mer_take_time[0]" placeholder="开始时间" value-format="HH:mm" />
            <el-time-picker v-model="info.mer_take_time[1]" placeholder="结束时间" value-format="HH:mm" />
          </el-form-item>
        </el-form>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button @click="diaLogChangeStatus">关 闭</el-button>
        <el-button type="primary" @click="submitEditInfo">提 交</el-button>
      </span>
    </el-dialog>
    <!-- 地图定位 -->
    <el-dialog
      v-if="modalMap"
      v-model="modalMap"
      :visible.sync="modalMap"
      title="选择位置"
      close-on-click-modal
      class="mapBox"
      custom-class="dialog-scustom"
      :append-to-body='true'
      width="80%" top="20px">
      <iframe id="mapPage" width="100%" height="700px" frameborder="0" :src="keyUrl" />
    </el-dialog>


  </div>
</template>

<script>
import { pointGetList, pointEdit, pointDel } from "@/api/product";
import {configApi} from "@/api/system";

export default {
  name: "Point",
  components: { },
  data() {
    return {
      listLoading: true,
      tableFrom: {
        page: 1,
        limit: 20,
        mer_take_name: '',
      },
      tableData: {
        data: [],
        total: 0
      },
      // 弹框
      info: {
        mer_take_name: '',
        mer_take_phone: '',
        mer_take_location: {},
        mer_take_address: '',
        mer_take_day: '',
        mer_take_time: {},
      },
      pointShow: false,
      rules: {
        mer_take_name: [{required: true, message: '请输入提货点名称', trigger: 'blur'}],
        mer_take_day: [{required: true, type: 'array', message: '请选择提货点营业日期', trigger: 'change'}],
        mer_take_phone: [{
          required: true, validator: function (rule, value, callback) {
            if (!value) {
              return callback(new Error('请填写手机号'))
            } else if (!/^1[3456789]\d{9}$/.test(value)) {
              callback(new Error('手机号格式不正确!'))
            } else {
              callback()
            }
          }, trigger: 'blur'
        }],
        mer_take_address: [{required: true, message: '请输入详细地址', trigger: 'blur'}],
        mer_take_location: [{
          required: true, validator: function (rule, value, callback) {
            if (Object.values(value).length <= 0) {
              return callback(new Error('请选择经纬度'))
            } else if (Number(value[0]) <= 0 || Number(value[1]) <= 0) {
              callback(new Error('请选择正确的经纬度!'))
            } else {
              callback()
            }
          }, trigger: 'blur'
        }],
        mer_take_time: [{
          required: true, validator: function (rule, value, callback) {
            if (Object.values(value).length <= 0) {
              return callback(new Error('请选择提货点营业时间'))
            } else {
              callback()
            }
          }, trigger: 'blur'
        }],
      },
      date: [
        { date_name: '周一', date_id: '1' },
        { date_name: '周二', date_id: '2' },
        { date_name: '周三', date_id: '3' },
        { date_name: '周四', date_id: '4' },
        { date_name: '周五', date_id: '5' },
        { date_name: '周六', date_id: '6' },
        { date_name: '周日', date_id: '7' }
      ],
      // 定位相关
      modalMap: false,
      mapKey: '',
      keyUrl: '',
      delivery_type: '',
    };
  },
  mounted() {
    window.addEventListener('message', function (event) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data
      // console.log(loc)
      if (loc && loc.module === 'locationPicker') {
        // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        window.parent.selectAddress(loc)
      }
    }, false)
    window.selectAddress = this.selectAddress

    this.getList("");
    this.getMapKey();
  },
  methods: {
    // 获取列表
    getList(num) {
      this.listLoading = true;
      this.tableFrom.page = num ? num : this.tableFrom.page;
      pointGetList(this.tableFrom).then(res => {
        this.tableData.data = res.data.list;
        this.tableData.total = res.data.count;
        this.listLoading = false;
      }).catch(res => {
        this.listLoading = false;
        this.$message.error(res.message);
      });
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList("");
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList(1);
    },
    // 定位处理 - 获取地图key
    getMapKey() {
      configApi().then(res => {
        // console.log(res);
        this.mapKey = res.data.tx_map_key
        const keys = res.data.tx_map_key
        this.keyUrl = `https://apis.map.qq.com/tools/locpicker?type=1&key=${keys}&referer=myapp`
        this.delivery_type = res.data.delivery_type
      }).catch(res => {
        this.$message.error(res.message)
      })
    },
    // 定位处理 - 显示弹框
    onSearchs() {
      if (!this.mapKey || this.mapKey == '') this.$message.error('平台未配置腾讯地图KEY')
      else this.modalMap = true
    },
    // 定位处理 - 选择经纬度
    selectAddress(data) {
      // console.log('经纬度信息', data)
      this.info.mer_take_location = [data.latlng.lat,data.latlng.lng]
      this.info.mer_take_address = data.poiaddress || ''
      this.modalMap = false
      this.$refs['editInfoField'].validate(valid => {});
      this.$forceUpdate();
    },
    // 提货点编辑弹框显示隐藏
    diaLogChangeStatus(){
      this.pointShow = !this.pointShow;
      if(!this.pointShow) this.info = this.$options.data().info;
    },
    // 信息操作 - 提交编辑
    submitEditInfo(){
      let _this = this;
      let info = Object.assign({}, this.info);
      this.$refs['editInfoField'].validate(valid => {
        if (valid) {
          pointEdit(info).then(res => {
            if(res.status == 200){
              _this.$message.success('操作成功');
              _this.diaLogChangeStatus();
              _this.getList(1);
              _this.$forceUpdate();
            }
          }).catch(res => {
            this.$message.error(res.message);
          });
        }
      });
    },
    // 信息操作 - 编辑
    editInfo(info){
      this.info = Object.assign({}, info);
      this.diaLogChangeStatus();
    },
    // 信息操作 - 删除
    deleteDel(id){
      let _this = this;
      _this.$confirm('删除后不可恢复，您确认删除吗?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '不删除',
        type: 'warning'
      }).then(() => {
        pointDel(id).then(({message}) => {
          _this.$message.success(message);
          _this.getList('');
        }).catch(({message}) => {
          _this.$message.error(message);
        });
      }).catch(action => {})
    },




  }
};
</script>

<style scoped lang="scss">
.mer-take-day{
  width: 100% !important;
}
</style>
