<template>
  <div class="execution">
    <basic-container>
      <avue-crud ref="crud"
                 :page="page"
                 v-model="form"
                 :data="tableData"
                 :table-loading="tableLoading"
                 :option="tableOption"
                 @on-load="getList"
                 @search-change="searchChange"
                 @refresh-change="refreshChange"
                 @size-change="sizeChange"
                 @current-change="currentChange"
                 @row-del="rowDel">
        <template slot="menuLeft" >
          <el-button v-if="permissionList.addBtn" type="primary" @click="addFn" :loading="infoExportAllLoading">新增<i class="el-icon-plus el-icon--right"></i></el-button>
          <el-button type="primary" @click="exportTaskInfoAll()" :loading="infoExportAllLoading">批量转换经纬度<i class="el-icon-download el-icon--right"></i></el-button>
          <el-button
            v-if="permissionList.addBtn"
            class="filter-item"
            type="primary"
            size="small"
            icon="el-icon-upload"
            @click="importUserOpen">批量导入
          </el-button>
        </template>
        <template
          slot="menu"
          slot-scope="scope">
          <el-button
            v-if="permissionList.editBtn"
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="editFn(scope.row,scope.index)">编辑
          </el-button>
        </template>
      </avue-crud>
    </basic-container>
    <!-- 新增/编辑 -->
    <el-dialog
      v-if="showAddDialog"
      :visible.sync="showAddDialog"
      :before-close="closeFn"
      :title="dialogType === 'add' ? '新增' : '编辑'">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="120px">
        <el-form-item label="药店名称：" prop="pharmacyName">
          <el-input v-model="form.pharmacyName" placeholder="请输入药店名称" />
        </el-form-item>
        <el-form-item label="医院城市：" prop="city">
          <span class="cityColor"  @click="toAddress">{{city}}</span>
        </el-form-item>
        <el-form-item label="地址：" prop="address">
          <div class="map" style="overflow: hidden;">
            <el-input v-model="addressKeyword" placeholder="请输入地址来直接查找相关位置" clearable style="margin-bottom:20px">
              <el-button slot="append" icon="el-icon-search" @click="getAddressKeyword"></el-button>
            </el-input>
            <div id="container" style="width:100%; height:300px"></div>
          </div>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="纬度：" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度：" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="药店类型：" prop="pharmacyType">
              <el-select v-model="form.pharmacyType" placeholder="请选择">
                <el-option
                  v-for="item in pharmacyTypeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="saveFn">保 存</el-button>
        <el-button type="default" size="small" @click="closeFn">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="addInp"
      :close-on-click-modal="true"
      title="请选择区域">
      <v-distpicker type="mobile" @selected='selected' v-show="addInp">
      </v-distpicker>
      <div slot="footer"
           class="dialog-footer">
        <el-button
          type="default"
          size="small"
          @click="addInp = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 批量导入 -->
    <el-dialog
      title="批量导入药店"
      :visible.sync="importUserShow"
      width="400px"
      :before-close="importUserClose"
    >
      <div class="tc" v-loading="importLoading">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="headers"
          :before-upload="importUserBefore"
          :on-preview="handleUserPreview"
          :on-remove="handleUserRemove"
          :before-remove="beforeUserRemove"
          :limit="1"
          :on-exceed="handleUserExceed"
          :on-success="handleUserSuccess"
          :on-error="handleUserError"
          accept=".xls,.xlsx"
          :file-list="userFileList"
          :show-file-list="false">
          <el-button size="small" type="primary">批量导入（*.xlsx,*.xls）</el-button>
        </el-upload>
        <br>
        <el-button type="text" @click="handleDown">下载模板</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="上传失败！"
      width="600px"
      :close-on-click-modal="false"
      @close="importErrorDialogClose"
      :visible.sync="importErrorDialogShow"
      center>
      <avue-crud
        style="width: 100%;"
        :data="importErrorTableData"
        :option="option1"
      >
      </avue-crud>
    </el-dialog>
  </div>
</template>

<script>
    import {fetchList, getObj, addObj, putObj, delObj,pageAudit} from '@/api/wmdapharmacy'
    import {tableOption} from '@/const/crud/wmdapharmacy'
    import {mapGetters} from 'vuex'
    import VDistpicker from 'v-distpicker'
    import maps from "qqmap"
    import store from "@/store";
    import {importErrorTableOption} from "@/const/crud/admin/user";
    import {templateDownload} from "@/api/assignPoints/currency/manList";
    import {parseAddressPharmacy} from "@/api/wmdahospital";
    import { getDictType } from "@/api/common";

    export default {
        name: 'wmdapharmacy',
        data() {
            return {
              pharmacyTypeArr: [],
              infoExportAllLoading: false,
              map: null,
              markerLayer: null, // 标记
              geocoder: null, // 正逆地址解析类
              getAddress: null,
              getAddCode: null,
              addressKeyword: "",
              shopInfo:{
                lng:null,
                lat:null
              },
              city:'请选择区域',
              addInp :false,
              mask:false,
              form: {},
              searchForm: {},
              tableData: [],
              page: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 20 // 每页显示多少条
              },
              tableLoading: false,
              tableOption: tableOption,
              showAddDialog: false,
              dialogType: 'add',
              formRules: {
                latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
                longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
                pharmacyType: [{ required: true, message: '请选择药店类型', trigger: 'change' }],
              },
              headers: {
                Authorization: 'Bearer ' + store.getters.access_token
              },
              importUserShow: false,
              importLoading: false,
              userFileList: [],
              importErrorDialogShow: false,
              uploadUrl: '',
              importErrorTableData: [],
              option1: importErrorTableOption
            }
        },
        computed: {
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: this.vaildData(this.permissions.admin_wmdapharmacy_add, false),
                    delBtn: this.vaildData(this.permissions.admin_wmdapharmacy_del, false),
                    editBtn: this.vaildData(this.permissions.admin_wmdapharmacy_edit, false)
                };
            }
        },
      components: {
        VDistpicker
      },
      mounted(){
        this.loadMapScript()
      },
      created() {
        this.getTypeArr()
      },
      destroyed() {
        if(this.map) {
          this.map.destroy()
          this.map = null
        }
      },
      methods: {
        getTypeArr() {
          getDictType({ type: 'pharmacy_type' }).then(res => {
            console.log('res', res);
            this.pharmacyTypeArr = res.data.data
          })
        },
        addFn () {
          this.addressKeyword=""
          this.city="请选择区域"
          this.dialogType = 'add'
          this.showAddDialog = true
          this.$nextTick(() => {
            this.init();
          })
        },
        editFn (row, index) {
          this.addressKeyword = row.address || ''
          this.city = (row.province || '') + ' ' + (row.city || '') + ' ' + (row.area || '')
          this.form = Object.assign({}, row)
          this.dialogType = 'edit'
          this.showAddDialog = true
          this.$nextTick(() => {
            this.init();
          })
        },
        saveFn() {
          this.form.address = this.addressKeyword
          if(!this.addressKeyword) {
            this.$message.error('地址不能为空')
            return
          }
          if(!this.form.pharmacyType) {
            this.$message.error('药店类型不能为空')
            return
          }
          if(!this.city) {
            this.$message.error('区域不能为空')
            return
          }
          if (this.dialogType === 'add') {
            addObj(this.form).then(res => {
              this.$message.success('添加成功')
              this.showAddDialog = false
              this.form = {
                yymc: '',
                address: '',
                latitude: '',
                longitude: '',
                yygm: '',
                yyxz: '',
                website: '',
                ybczs: ''
              }
              this.getList(this.page)
            }).catch(() => {})
          } else {
            putObj(this.form).then(res => {
              this.$message.success('修改成功')
              this.showAddDialog = false
              this.form = {
                yymc: '',
                address: '',
                latitude: '',
                longitude: '',
                yygm: '',
                yyxz: '',
                website: '',
                ybczs: ''
              }
              this.getList(this.page)
            }).catch(() => {})
          }
        },
        closeFn () {
          this.map.off("click", this.clickHandler)
          this.map = null
          this.markerLayer = null // 标记
          this.geocoder = null // 正逆地址解析类
          this.showAddDialog = false
          this.form = {
            yymc: '',
            address: '',
            latitude: '',
            longitude: '',
            yygm: '',
            yyxz: '',
            website: '',
            ybczs: ''
          }
        },
        // https://lbs.qq.com/webApi/javascriptGL/glGuide/glBasic
        loadMapScript() {
          var script = document.createElement("script");
          script.type = "text/javascript";
          script.src = "https://map.qq.com/api/gljs?v=1.exp&libraries=service&key=C4ABZ-HWE3X-5DW4J-ZO4GH-IQBWK-TXF2X";
          document.body.appendChild(script);
        },
        init() {
          //定义地图中心点坐标
          var center = new TMap.LatLng(22.547931568083015, 114.1306221485138)
          //定义map变量，调用 TMap.Map() 构造函数创建地图
          this.map = new TMap.Map(document.getElementById('container'), {
            center: center,//设置地图中心点坐标
            zoom:16,   //设置地图缩放级别
            viewMode: '2D' // 可选 2D 3D
          });
          // 新建一个正逆地址解析类
          this.geocoder = new TMap.service.Geocoder();
          //初始化marker图层
          this.markerLayer = new TMap.MultiMarker({
            id: 'marker-layer',
            map: this.map
          });
          this.map.on("click",this.clickHandler)
          this.getAddressKeyword()
        },
        clickHandler (event) {
          // 获取点击后的地图坐标
          this.shopInfo.lng = event.latLng.getLng();
          this.shopInfo.lat = event.latLng.getLat();
          this.getAddressCode();
          this.removeMarker()
          this.markerLayer.add({
            position: event.latLng
          });
        },
        //移除marker事件
        removeMarker() {
          const markList = this.markerLayer.getGeometries()
          if (this.markerLayer && markList.length > 0) {
            this.markerLayer.remove(markList[0].id);
          }
        },
        getAddressKeyword() {
          const convert = () => {
            // 将给定的地址转换为坐标位置
            const cityText = this.city === '请选择区域' ? '' : this.city.replace(/\s*/g, '') || ''
            const address = cityText + this.addressKeyword
            this.geocoder
              .getLocation({ address })
              .then((result) => {
                this.removeMarker()
                this.$nextTick(() => {
                  this.markerLayer.updateGeometries([{
                    position: result.result.location, // 将得到的坐标位置用点标记标注在地图上
                  }]);
                })
                this.map.setCenter(result.result.location);
                this.form.longitude = result.result.location.lng;
                this.form.latitude = result.result.location.lat;
              });
          }
          if (this.addressKeyword) {
            convert()
          }
        },
        // 通过坐标获得地址
        getAddressCode() {
          var lat = parseFloat(this.shopInfo.lat);
          var lng = parseFloat(this.shopInfo.lng);
          var location = new TMap.LatLng(lat, lng);
          this.geocoder.getAddress({ location: location }) // 将给定的坐标位置转换为地址
            .then((result) => {
              this.addressKeyword = result.result.address || ''
            });
          this.form.longitude=lng;
          this.form.latitude=lat;
        },
        toAddress(){
          this.mask = true;
          this.addInp = true;
        },
        // 省市区三级联动
        selected(data){
          this.mask =false;
          this.addInp = false;
          this.city = data.province.value + ' ' + data.city.value +' ' + data.area.value
          this.form.province=data.province.value;
          this.form.city=data.city.value;
          this.form.area=data.area.value;
          //this.city =  data.area.value
          this.addressKeyword=data.province.value + data.city.value+ data.area.value
          this.getAddressKeyword()
        },
        getList(page, params) {
          this.tableLoading = true
          fetchList(Object.assign({
            current: page.currentPage,
            size: page.pageSize
          }, params, this.searchForm )).then(response => {
            this.tableData = response.data.data.records
            this.page.total = response.data.data.total
            this.tableLoading = false
          }).catch(() => {
            this.tableLoading=false
          })
        },
        rowDel: function (row, index) {
          this.$confirm('是否确认删除ID为' + row.id, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(function () {
            return delObj(row.id)
          }).then(data => {
            this.$message.success('删除成功')
            this.getList(this.page)
          })
        },
        sizeChange(pageSize){
          this.page.pageSize = pageSize
        },
        currentChange(current){
          this.page.currentPage = current
        },
        searchChange(form, done) {
          this.searchForm = form
          this.page.currentPage = 1
          this.getList(this.page, form)
          done()
        },
        refreshChange() {
          this.getList(this.page)
        },
        exportTaskInfoAll(){
          this.infoExportAllLoading=true
          parseAddressPharmacy().then(data => {
            this.$message.success('地址转换成功')
            this.infoExportAllLoading=false
          }).catch(() => {
            loading();
          });
        },
        // 以下为批量导入功能
        importUserClose() {
          this.importUserShow = false
          this.userFileList = []
        },
        importUserBefore() {
          this.importLoading = true
        },
        beforeUserRemove(file, fileList) {
          return this.$confirm(`确定移除 ${ file.name }？`);
        },
        handleUserRemove(file, fileList) {
          console.log(file, fileList);
        },
        handleUserPreview(file) {
          console.log(file);
        },
        handleUserExceed(files, fileList) {
          this.$message.warning('最多上传一个文件');
        },
        handleUserSuccess(res, file) {
          this.importLoading = false
          if (res.code === 1) {
            this.userFileList = []
            if (res.data && res.data.code === 'FAILURE') { // 上传有错误
              this.importErrorTableData = []
              const errorData = res.data.data
              if (Object.keys(errorData).length > 0) {
                Object.keys(errorData).forEach(ele => {
                  this.importErrorTableData.push({ reason: ele, index: errorData[ele] })
                })
              }
              console.log(this.importErrorTableData);
              this.importErrorDialogShow = true
            } else { // 上传失败
              this.$message.error(res.msg)
            }
          } else {
            this.$message.success('上传成功！')
            this.importUserClose()
            this.getList(this.page)
          }
        },
        handleUserError(err) {
          this.$message.error('上传失败！')
          this.importLoading = false
        },
        handleDown() {
          this.importLoading = true
          templateDownload({
            fileName: 'batch_create_pharmacy_template.xlsx'
          }).then(response => {
            this.importLoading = false
            let url = window.URL.createObjectURL(new Blob([response.data]))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '批量导入药店模板.xlsx')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }).catch(() => {
            this.importLoading = false
          })
        },
        importErrorDialogClose() {
          this.importErrorDialogShow = false
        },
        // 导入用户
        importUserOpen() {
          this.uploadUrl = 'admin/wmdapharmacy/batch'
          this.importUserShow = true
        }
      }
    }
</script>
<style lang="less">

  .distpicker-address-wrapper{
    color: #000000 !important;
  }


  .distpicker-address-wrapper .address-header ul li.active{
    color: #000000 !important;
  }

  .cityColor{
    color: #2d8cf0;
  }
</style>
