<template>
  <div class="app-container calendar-list-container">
    <div>
      <div class="filter-container" ref="filter-container">
        <div class="top_btn">
          <el-button
            type="primary"
            @click="add_item"
            icon="el-icon-plus"
            v-show="elements['btn_add_stroe']"
          >添加门店</el-button>
        </div>
        <el-form ref="queryForm" :inline="inline" :model="listQuery" label-width="80px">
          <el-row>
            <el-form-item label="省市">
              <el-select
                v-model="listQuery.provinceCode"
                placeholder="请选择"
                @change="changeProvince_search"
                filterable
              >
                <el-option
                  v-for="item in provinceArr"
                  :key="item.id"
                  :label="item.name"
                  :value="item.agencyId"
                ></el-option>
              </el-select>

              <el-select v-model="listQuery.cityCode" placeholder="请选择" filterable>
                <el-option
                  v-for="item in cityArrs"
                  :key="item.id"
                  :label="item.name"
                  :value="item.agencyId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="门店名称">
              <el-input v-model="listQuery.name" placeholder="请输入公司名称"></el-input>
            </el-form-item>
            <el-form-item label="所属公司">
              <el-select v-model="listQuery.companyId">
                <el-option
                  v-for="(item,idx) in companys_list"
                  :key="idx"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-button
              class="filter-item"
              type="primary"
              v-waves
              icon="el-icon-search"
              @click="handleFilter"
            >搜索</el-button>
            <el-button class="filter-item" @click="clear_handleFilter">清除搜索</el-button>
          </el-row>
        </el-form>
      </div>
      <el-table :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;">
        <el-table-column align="center" label="序号" type="index" width="100">
          <template slot-scope="scope">
            <span>{{(listQuery.page - 1) * listQuery.limit + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="门店全称" prop="name"></el-table-column>
        <el-table-column align="center" label="门店简称" prop="shortName"></el-table-column>
        <el-table-column align="center" label="状态" prop="legalPerson">
          <template slot-scope="{row}">
            <span v-if="row.state==1">上架</span>
            <span v-else>下架</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="所属公司" prop="companyName"></el-table-column>
        <el-table-column align="center" label="负责人" prop="leader"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="{row}">
            <el-button type="text" @click="edit_item(row)" v-show="elements['btn_edit_stroe']">编辑</el-button>
            <el-button
              type="text"
              @click="updateState(row,2)"
              v-show="elements['btn_up_down_stroe']"
              v-if="row.state==1"
            >下架</el-button>
            <el-button
              type="text"
              @click="updateState(row,1)"
              v-show="elements['btn_up_down_stroe']"
              v-if="row.state==2"
            >上架</el-button>
            <el-button type="text" @click="del_item(row)" v-show="elements['btn_del_stroe']">删除</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,40,50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      :title="title_text"
      width="50%;"
      :visible.sync="add_edit_dialog"
      @close="add_edit_dialog=false"
    >
      <div class="form_box1">
        <el-form ref="store_form" :rules="rules" :model="store_form" style label-width="100px">
          <el-form-item label="状态">
            <el-radio-group v-model="store_form.state">
              <el-radio :label="1">上架</el-radio>
              <el-radio :label="2">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="门店全称" prop="name">
            <el-input v-model="store_form.name" style="width:30%"></el-input>
          </el-form-item>
          <el-form-item label="门店简称" prop="sortName">
            <el-input v-model="store_form.sortName" style="width:30%"></el-input>
          </el-form-item>
          <el-form-item label="门店图片" prop="sortPic">
            <el-upload
              class="avatar-uploader"
              :action="BASE_API+'/api/universal/file/app/unauth/admin/upload'"
              :show-file-list="false"
              :headers="getHeaderWithToken"
              :on-success="handleAvatarSuccess"
            >
              <img
                v-if="$utils.isString(store_form.sortPic) && !$utils.isEmpty(store_form.sortPic)"
                :src="store_form.sortPic"
                style="width:200px;max-height:200px;"
              />
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
                style="lineHeight:100px;width:100px;height: 100px;vertical-align: middle;"
              ></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="所属公司" prop="companyid">
            <el-select v-model="store_form.companyid" style="width:30%">
              <el-option
                v-for="(item,idx) in companys_list"
                :key="idx"
                :label="item.name"
                :value="item.id+''"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责人" prop="dutyName">
            <el-input v-model="store_form.dutyName" style="width:30%"></el-input>
          </el-form-item>
          <el-form-item label="负责人手机" prop="phone">
            <el-input v-model="store_form.phone" style="width:30%"></el-input>
          </el-form-item>
          <el-form-item label="地区" prop="city">
            <el-select
              style="width:20%"
              v-model="store_form.province"
              placeholder="请选择"
              @change="changeProvince"
              filterable
            >
              <el-option
                v-for="item in provinceArr"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>

            <el-select
              v-model="store_form.city"
              @change="changeCity"
              placeholder="请选择"
              style="width:20%"
              filterable
            >
              <el-option
                v-for="item in cityArrs"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
            <el-select
              style="width:20%"
              v-model="store_form.county"
              @change="changeCounty"
              placeholder="请选择"
              filterable
            >
              <el-option
                v-for="item in regionArr"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="详细地区" prop="detail_address">
            <el-input v-model="store_form.detail_address" @blur="get_detail_jw" style="width:60%"></el-input>
          </el-form-item>
          <el-form-item label="经纬度">
            <el-input
              disabled
              :value="store_form.longitude+','+store_form.latitude"
              style="width:60%"
            ></el-input>
            <span>点击地图自动获取经纬度</span>
          </el-form-item>
        </el-form>
        <div class="map_box">
          <baidu-map
            class="map"
            :center="center"
            :zoom="zoom"
            @ready="handler"
            style="width:100%;height: 500px"
            :scroll-wheel-zoom="true"
            @click="clickEvent"
            ak="33B192o1jPaqOHASGGAIkoMuwi8W76j3"
          >
            <bm-local-search
              :keyword="keyword"
              :auto-viewport="true"
              :location="location"
              style="display: none"
            ></bm-local-search>
            <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
            <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
            <bm-geolocation
              anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
              :showAddressBar="true"
              :autoLocation="true"
              @locationSuccess="getLoctionSuccess"
            ></bm-geolocation>
            <bm-view
              :style="{width:'100%',height: this.clientHeight+'px',flex: 1,marginBottom:'-30px'}"
            ></bm-view>
          </baidu-map>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="add_edit_dialog = false">取 消</el-button>
        <el-button type="primary" v-if="title_text=='添加门店'" @click="add_store_ok('store_form')">确 定</el-button>
        <el-button
          type="primary"
          v-if="title_text=='修改门店'"
          @click="update_store_ok('store_form')"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script type="javascript">
import { formatDate } from "utils/dateFormattor";
import { getSonRegionByType, getSons } from "api/trouSys";
import {
  toEast8Date,
  deepCopyDate,
  newEast8Date,
  convertDate2Str,
  timestamp2Date,
} from "utils/dateUtils";

import { mapGetters } from "vuex";

import {
  store_list,
  company_all_list,
  add_store,
  update_store,
  del_store,
} from "api/company";
import { getAllZone } from "api/base_info/constant/";
import Element1 from "../admin/menu/components/element";
import ElRow from "element-ui/packages/row/src/row";
import ElCol from "element-ui/packages/col/src/col";
import { getToken } from "utils/auth";

export default {
  name: "carApplyList",
  components: {
    ElCol,
    ElRow,
    Element1,
  },
  data() {
    var validatemobile = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      title_text: "",
      BASE_API: process.env.BASE_API,
      add_edit_dialog: false,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        companyId: undefined,
        provinceCode: null, //省
        provinceName: null, //省
        cityCode: null, //市
        cityName: null, //市
      },
      companys_list: [],
      inline: true,
      tableKey: 0,
      rules: {
        name: [{ required: true, message: "请输入门店名称", trigger: "blur" }],
        sortName: [
          { required: true, message: "请输入门店简称", trigger: "blur" },
        ],
        sortPic: [
          { required: true, message: "请上传门店图片", trigger: "blur" },
        ],
        companyid: [
          { required: true, message: "请选择所属公司", trigger: "blur" },
        ],
        dutyName: [
          { required: true, message: "请输入负责人", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入负责人手机", trigger: "blur" },
          { validator: validatemobile, trigger: "blur" },
        ],
        province: [{ required: true, message: "请选择省份", trigger: "blur" }],
        city: [{ required: true, message: "请选择城市", trigger: "blur" }],
        detail_address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
      },
      store_form: {
        id: "",
        name: "",
        state: 1,
        sortName: "",
        sortPic: "",
        companyid: "",
        dutyName: "",
        phone: "",
        province: "",
        city: "",
        county: "",
        detail_address: "",
        latitude: undefined, //纬度
        longitude: undefined, //经度
      },
      provinceArr: [],
      cityArrs: [],
      regionArr: [],
      center: { lng: 113.75179, lat: 23.02067 },
      zoom: 12,
      keyword: "",
      location: "",
      clientHeight: 500, // 屏幕高度
      btn_disable: null,
      move_center: { lng: 113.75179, lat: 23.02067 },
    };
  },
  mounted() {},
  created() {
    this.getList();
    this.get_all_companys();
    getSonRegionByType().then((data) => {
      this.provinceArr = data.data;
    });
  },
  computed: {
    ...mapGetters(["elements"]),
    getHeaderWithToken() {
      return { Authorization: getToken() };
    },
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.store_form.sortPic = res.data;
    },
    //修改
    update_store_ok(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          let addr_province = undefined;
          let addr_city = undefined;
          let addr_county = undefined;
          if (
            this.provinceArr.length > 0 &&
            this.store_form.province &&
            this.store_form.province != ""
          ) {
            addr_province = this.provinceArr.filter(
              (item) => item.name == this.store_form.province
            )[0].id;
          }
          if (
            this.cityArrs.length > 0 &&
            this.store_form.city &&
            this.store_form.city != ""
          ) {
            addr_city = this.cityArrs.filter(
              (item) => item.name == this.store_form.city
            )[0].id;
          }
          if (
            this.regionArr.length > 0 &&
            this.store_form.county &&
            this.store_form.county != ""
          ) {
            addr_county = this.regionArr.filter(
              (item) => item.name == this.store_form.county
            )[0].id;
          }
          let data = {
            id: this.store_form.id,
            name: this.store_form.name,
            state: this.store_form.state,
            shortName: this.store_form.sortName,
            companyPic: this.store_form.sortPic,
            companyId: this.store_form.companyid,
            leader: this.store_form.dutyName,
            phone: this.store_form.phone,
            provinceName: this.store_form.province,
            addrProvince: addr_province,
            addrCity: addr_city,
            addrTown: addr_county,
            cityName: this.store_form.city,
            townName: this.store_form.county,
            addrDetail: this.store_form.detail_address,
            latitude: this.store_form.latitude, //纬度
            longitude: this.store_form.longitude, //经度
            isShow: 1, // 1、app展示
          };
          update_store(this.store_form.id, data).then((res) => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "修改成功!",
              });
              this.add_edit_dialog = false;
              this.handleFilter();
            } else {
              this.$message({
                type: "info",
                message: res.message,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    //添加
    add_store_ok(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          this.btn_disable = true;
          let addr_province = undefined;
          let addr_city = undefined;
          let addr_county = undefined;
          if (this.store_form.province && this.store_form.province != "") {
            addr_province = this.provinceArr.filter(
              (item) => item.name == this.store_form.province
            )[0].id;
          }
          if (this.store_form.city && this.store_form.city != "") {
            addr_city = this.cityArrs.filter(
              (item) => item.name == this.store_form.city
            )[0].id;
          }
          if (this.store_form.county && this.store_form.county != "") {
            addr_county = this.regionArr.filter(
              (item) => item.name == this.store_form.county
            )[0].id;
          }
          let data = {
            name: this.store_form.name,
            state: this.store_form.state,
            shortName: this.store_form.sortName,
            companyPic: this.store_form.sortPic,
            companyId: this.store_form.companyid,
            leader: this.store_form.dutyName,
            phone: this.store_form.phone,
            provinceName: this.store_form.province,
            addrProvince: addr_province,
            addrCity: addr_city,
            addrTown: addr_county,
            cityName: this.store_form.city,
            townName: this.store_form.county,
            addrDetail: this.store_form.detail_address,
            latitude: this.store_form.latitude, //纬度
            longitude: this.store_form.longitude, //经度
            isShow: 1, // 1、app显示
          };
          let that = this;
          add_store(data).then((res) => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "添加成功!",
              });
              this.add_edit_dialog = false;
              this.handleFilter();
            } else {
              this.$message({
                type: "info",
                message: res.message,
              });
            }
            that.btn_disable = null;
          });
        } else {
          return false;
        }
      });
    },
    edit_item(row) {
      console.log(row);
      this.store_form = {
        id: row.id,
        name: row.name,
        state: row.state,
        sortName: row.shortName,
        sortPic: row.companyPic,
        companyid: String(row.companyId),
        dutyName: row.leader,
        phone: row.phone,
        //  addr_province,
        //    addr_city,
        //    addr_county,
        province: row.provinceName,
        city: row.cityName,
        county: row.townName,
        detail_address: row.addrDetail,
        latitude: row.latitude, //纬度
        longitude: row.longitude, //经度
      };
      this.add_edit_dialog = true;
      this.title_text = "修改门店";
    },
    updateState(row, type) {
      let data = {
        id: row.id,
        state: type,
      };
      update_store(row.id, data).then((res) => {
        if (res.status == 200) {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.handleFilter();
        } else {
          this.$message({
            type: "info",
            message: res.message,
          });
        }
      });
    },
    //删除
    del_item(row) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          del_store({ id: row.id }).then((res) => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.handleFilter();
            } else {
              this.$message({
                type: "info",
                message: res.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //点击地图回显地址
    get_detail_jw() {
      this.keyword =
        this.store_form.province +
        this.store_form.city +
        this.store_form.county +
        this.store_form.detail_address;
    },
    handler({ BMap, map }) {
      let _this = this; // 设置一个临时变量指向vue实例，因为在百度地图回调里使用this，指向的不是vue实例；
      var geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(
        function (r) {
          console.log(r);
          if (_this.store_form.longitude && _this.store_form.latitude) {
            _this.center = {
              lng: _this.store_form.longitude,
              lat: _this.store_form.latitude,
            }; // 设置center属性值
            _this.autoLocationPoint = {
              lng: _this.store_form.longitude,
              lat: _this.store_form.latitude,
            }; // 自定义覆盖物
          } else {
            _this.center = { lng: r.longitude, lat: r.latitude }; // 设置center属性值
            _this.autoLocationPoint = { lng: r.longitude, lat: r.latitude }; // 自定义覆盖物
          }
          _this.initLocation = true;
        },
        { enableHighAccuracy: true }
      );

      window.map = map;
    },
    //定位成功回调
    getLoctionSuccess(point, AddressComponent, marker) {
      map.clearOverlays();
      if (this.store_form.longitude && this.store_form.latitude) {
        point.point.lng = this.store_form.longitude;
        point.point.lat = this.store_form.latitude;
      }
      let Icon_0 = new BMap.Icon(
        "https://imgtest.upyuns.com/wx324f946efef2ca02/admin/2020-06-06/1.png",
        new BMap.Size(64, 64),
        { anchor: new BMap.Size(18, 32), imageSize: new BMap.Size(36, 36) }
      );
      var myMarker = new BMap.Marker(
        new BMap.Point(point.point.lng, point.point.lat),
        { icon: Icon_0 }
      );
      map.addOverlay(myMarker);
    },
    //点击地图监听
    clickEvent(e) {
      map.clearOverlays();
      let Icon_0 = new BMap.Icon(
        "https://imgtest.upyuns.com/wx324f946efef2ca02/admin/2020-06-06/1.png",
        new BMap.Size(64, 64),
        { anchor: new BMap.Size(18, 32), imageSize: new BMap.Size(36, 36) }
      );
      var myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat), {
        icon: Icon_0,
      });
      map.addOverlay(myMarker);
      //用所定位的经纬度查找所在地省市街道等信息
      var point = new BMap.Point(e.point.lng, e.point.lat);
      var gc = new BMap.Geocoder();
      let _this = this;
      gc.getLocation(point, function (rs) {
        var addComp = rs.addressComponents;
        _this.changeProvince(rs.addressComponents.province);
        _this.changeCity(rs.addressComponents.city);
        _this.store_form.province = rs.addressComponents.province;
        _this.store_form.city = rs.addressComponents.city;
        if (rs.addressComponents && rs.addressComponents != "") {
          _this.store_form.detail_address =
            rs.addressComponents.street + rs.addressComponents.streetNumber;
          // _this.listQuery.address = rs.address;
        }
      });

      this.store_form.longitude = e.point.lng;
      this.store_form.latitude = e.point.lat;
    },
    //根据省拿市
    changeProvince_search(value) {
      if (!!this.listQuery.cityName) {
        this.listQuery.cityName = null;
      }

      getSons(this.provinceArr.filter((item) => item.id == value)[0].id).then(
        (data) => {
          this.cityArrs = data.data;
        }
      );
    },
    changeProvince(value) {
      if (!!this.store_form.city) {
        this.store_form.city = null;
      }

      getSons(this.provinceArr.filter((item) => item.name == value)[0].id).then(
        (data) => {
          this.cityArrs = data.data;
        }
      );
    },
    changeCity(value) {
      if (!!this.store_form.county) {
        this.store_form.county = null;
      }
      getSons(this.cityArrs.filter((item) => item.name == value)[0].id).then(
        (data) => {
          this.regionArr = data.data;
        }
      );
    },
    changeCounty() {
      this.keyword =
        this.store_form.province +
        this.store_form.city +
        this.store_form.county;
    },
    //获取所有公司
    get_all_companys() {
      company_all_list().then((res) => {
        if (res.status == 200) {
          this.companys_list = res.data;
        }
      });
    },

    form_clear() {
      this.store_form = {
        name: "",
        state: 1,
        sortName: "",
        sortPic: "",
        companyid: "",
        dutyName: "",
        phone: "",
        province: "",
        city: "",
        county: "",
        detail_address: "",
        latitude: null, //纬度
        longitude: null, //经度
      };
    },
    /**
     * 获取列表
     * */
    getList() {
      this.listLoading = true;
      let data = {
        page: this.listQuery.page,
        limit: this.listQuery.limit,
        addrCity: this.listQuery.cityCode,
        addrProvince: this.listQuery.provinceCode,
        name: this.listQuery.name,
        companyId: this.listQuery.companyId,
      };

      store_list(data).then((response) => {
        let totalCountRs = undefined;
        let listRs = undefined;
        if (
          !this.$utils.isEmpty(response.data.data) &&
          this.$utils.isInteger(response.data.totalCount)
        ) {
          listRs = response.data.data;
          totalCountRs = response.data.totalCount;
        }
        this.listLoading = false;
        this.list = listRs;
        this.total = totalCountRs;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          this.getList();
        } else {
          return false;
        }
      });
    },
    clear_handleFilter() {
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined,
        companyId: undefined,
        provinceCode: null, //省
        provinceName: null, //省
        cityCode: null, //市
        cityName: null, //市
      };
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    add_item() {
      this.add_edit_dialog = true;
      this.title_text = "添加门店";
      this.form_clear();
    },
  },
};
</script>
<style scoped>
.top_btn {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.form_box1 {
  height: 60vh;
  overflow-y: scroll;
  display: flex;
  flex-direction: column;
}

.map {
  position: relative;
  width: 100%;
  height: 500px;
}

.map_box {
  width: 100%;
  height: 500px;
}
</style>
