<template>
  <!-- 销售门店管理 -->
  <div>
    <actionBar menuTitle="销售门店管理" :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm"
      @openModel="openModel" @searchProtocol="searchProtocol"></actionBar>
    <treeTable :suspension="true" :treeData="treeData" :treeDataList="treeDataList" @buttonData="buttonData">
    </treeTable>
    <el-dialog :title="shopTitle" :visible.sync="shopDialogVisible" width="60%" :close-on-click-modal="false"
      @close="closeDialog">
      <forms ref="childRules" :formNewList="formRuleList" :ruleForm="ruleForm"></forms>
      <span slot="footer" class="dialog-footer" v-if="operationType != 'logs'">
        <el-button plain @click="shopDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 气瓶追溯 -->
    <div class="card_tracing">
      <el-dialog :visible.sync="cylinderTracingVisible" fullscreen :close-on-click-modal="false">
        <div style="width: 100%;height: 100vh;">
          <map-container ref="mapTracing" @close="close"></map-container>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {
    getStore,
    getStoreDetails,
    addStore,
    putStore,
    enterStore,
    delStore
  } from '@/api/shop'
  import actionBar from '@/components/actionBar'
  import treeTable from '@/components/treeTable'
  import forms from '@/components/forms'
  import MapContainer from '@/components/MapContainer'
  import {
    generatorDynamicRouter
  } from '@/router/generator-routers'
  import {
    rules,
    formRules
  } from "./outlet.js";
  import router, {
    resetRouter
  } from '../../router'
  import {
    urbanArea
  } from '@/assets/js/districtCode'
  import axios from 'axios'
  export default {
    components: {
      actionBar,
      treeTable,
      forms,
      MapContainer
    },
    data() {
      return {
        formList: [{
          type: 'input',
          label: '销售门店',
          field: 'name',
          placeholder: '请输入销售门店名称查找',
        }],
        searchRuleForm: {
          name: '',
        },
        operateList: [
          //   {
          //   type: 'ascend',
          //   title: '门店气瓶追溯',
          //   icon: 'el-icon-map-location',
          // },
          {
            type: 'add',
            title: '添加一级销售门店',
            icon: 'el-icon-plus',
          }
        ],
        treeData: rules(),
        treeDataList: [],
        shopDialogVisible: false,
        shopTitle: '添加',
        formRuleList: [],
        cylinderTracingVisible: false,
        ruleForm: {},
        parentId: 0,
        operationType: '',
        enterpriseId: null,
        confirmLoading: false,
        searchValue: {},
      }
    },
    mounted() {
      this.getList()
      const dataList = formRules();
      this.formRuleList = dataList;
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.searchValue = value
        this.getList()
      },
      getList() {
        getStore(this.searchValue).then(res => {
          if (res.code == 200) {
            this.treeDataList = res.data
          }
        })
      },
      openModel(type) {
        this.operationType = type
        if (type == 'add') {
          this.staffTitle = '添加'
          this.shopDialogVisible = true
        } else if (type == 'ascend') {
          this.cylinderTracingVisible = true
          this.$nextTick(() => {
            this.$refs.mapTracing.keyUpSearch()
          })
        }
      },
      // 获取经纬度
      longitudeLatitude(value) {
        var cityArr = urbanArea()
        var city = this.cityScreening(value.city, cityArr)
        var area = this.cityScreening(value.district, cityArr)
        return new Promise((resolve, inject) => {
          axios.get('https://restapi.amap.com/v3/geocode/geo', {
            params: {
              key: 'fcddcc366fd5bd355e35f01b7cce82ef',
              address: city + area + value.address,
            }
          }).then((res) => {
            resolve(res.data.geocodes[0])
          }).catch(() => {
            this.confirmLoading = false
          })
        })
      },
      // 城市筛选
      cityScreening(value, list) {
        function getChildById(parentArray, id) {
          for (let i = 0; i < parentArray.length; i++) {
            if (parentArray[i].value === id) { // 如果当前元素的ID与目标ID相等，则返回该元素
              return parentArray[i];
            } else if (parentArray[i].children && Array.isArray(parentArray[i].children)) { // 判断当前元素是否有子节点且类型为数组
              const result = getChildById(parentArray[i].children, id); // 对子节点进行递归调用
              if (result !== null) { // 若子节点存在结果，则返回该结果
                return result;
              }
            }
          }
          return null; // 没有找到符合条件的元素时返回null
        }
        var name = getChildById(list, value)
        if (name != null) {
          return name.label
        }
      },
      // 弹窗表单添加
      async handleAdd() {
        if (this.operationType == 'add') {
          let flag = this.$refs['childRules'].validateForm();
          if (flag) {
            this.confirmLoading = true
            this.ruleForm.type = Number(this.ruleForm.type)
            var params = {
              ...this.ruleForm
            }
            params.city = this.ruleForm.cityRegion[0]
            params.district = this.ruleForm.cityRegion[1]
            delete params.cityRegion;
            let arr = await this.longitudeLatitude(params)
            var propertyName = arr.location.split(",")
            params.lng = Number(propertyName[0])
            params.lat = Number(propertyName[1])
            await addStore({
              parentId: this.parentId,
              provStore: params
            }).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.shopDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          } else {
            this.$message.error('表单信息不完整，请继续填写完整');
          }
        } else if (this.operationType == 'edit') {
          this.editItem()
        }
      },
      // 修改
      async editItem() {
        let flag = this.$refs['childRules'].validateForm();
        if (flag) {
          this.confirmLoading = true
          this.ruleForm.type = Number(this.ruleForm.type)
          var params = {
            ...this.ruleForm
          }
          params.city = this.ruleForm.cityRegion[0]
          params.district = this.ruleForm.cityRegion[1]
          delete params.cityRegion;
          let arr = await this.longitudeLatitude(params)
          var propertyName = arr.location.split(",")
          params.lng = Number(propertyName[0])
          params.lat = Number(propertyName[1])
          await putStore({
            id: this.enterpriseId,
            provStore: params
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.getList()
            }
            this.shopDialogVisible = false
            this.confirmLoading = false
          }).catch(() => {
            this.confirmLoading = false
          })
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      // 进入
      enterInto(id) {
        enterStore({
          id: id,
        }).then(res => {
          if (res.code == 200) {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            const {
              token
            } = localStorage.getItem('T_tokey')
            generatorDynamicRouter(token).then(routers => {
              resetRouter()
              router.addRoutes(routers)
              this.$store.commit('setMenu', routers)
              this.$store.commit('SET_ROUTERS', routers)
            }).catch(e => {
              // console.log(e, '获取失败')
            })
          }
        })
      },
      // 删除
      deleteItem(id) {
        this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delStore({
            id: id,
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.getList()
            }
          })
        }).catch(() => {});
      },
      // 表格操作按钮
      buttonData(row, type) {
        this.enterpriseId = row.id
        this.operationType = type
        if (type == 'add') {
          this.shopTitle = '添加'
        } else if (type == 'edit') {
          this.shopTitle = '修改'
        } else if (type == 'logs') {
          this.formRuleList.forEach((item, index) => {
            item.disabled = true
          })
          this.shopTitle = '详情'
        }
        if (type == 'del') {
          this.deleteItem(row.id)
        } else if (type == 'edit' || type == 'logs') {
          if (row.provStore) {
            this.$nextTick(() => {
              this.ruleForm = JSON.parse(JSON.stringify(row.provStore))
              this.ruleForm.type = String(this.ruleForm.type)
              var arr = []
              arr.push(row.provStore.city)
              arr.push(row.provStore.district)
              this.ruleForm.cityRegion = arr
            })
          }
          this.shopDialogVisible = true
        } else if (type == 'add') {
          this.parentId = row.id
          this.shopDialogVisible = true
        } else if (type == 'entry') {
          // 进入
          this.$store.commit('SET_NAME', row.name)
          localStorage.setItem('companyName', row.name);
          this.enterInto(row.id)
        }
      },
      // 关闭地图弹窗
      close() {
        this.cylinderTracingVisible = false
      },
      closeDialog() {
        this.ruleForm = {}
        this.formRuleList.forEach((item, index) => {
          item.disabled = false
        })
        this.$refs.childRules.resetCheck();
      }
    }
  }
</script>

<style lang="scss" scoped>
  .card_tracing ::v-deep .el-dialog {
    margin-top: unset !important;
  }

  .card_tracing ::v-deep .el-dialog__header {
    border-bottom: unset !important;
    margin-bottom: unset !important;
    padding: 0px !important;
  }

  .card_tracing ::v-deep .el-dialog__body {
    padding: 0px !important;
  }

  .amap-logo {
    display: none !important;
    left: 0;
    height: 17px;
    margin: 0 1px;
  }

  .amap-copyright {
    display: none !important;
    left: 70px;
    height: 16px;
    font-size: 11px;
  }
</style>
