<template>
  <div class="page-box">
    <moduleView :propConfig="config" ref="view" v-loading="load" @pagination="pagination" @onRefresh="getList" @resert="queryList" @search="queryList" @detail="detail" @clickHandle="clickHandle" @modalHandle="modalHandle"/>
    <equipModal ref="equipModalView" @successHandle="getList" />
    <!-- <noAddEquip ref="noAddEquipView" @successHandle="getList" @addEquipClose="addEquipCloseHandle" /> -->
  </div>
</template>

<script setup>
  import { computed,getCurrentInstance,ref  } from "vue";
  const { proxy } = getCurrentInstance();
  import {listShop,delShop,addShop,updateShop} from '@/api/base/shopManage'
  import mapRang from "./mapRang.vue";
  import equipModal from "./equipModal.vue";
  import address from '@/components/address/address.vue';
  // import noAddEquip from "./noAddEquip.vue";

  const config = ref({
    attr:{
      calculateH:true
    },
    search:{
      attr:{
        size:'mini'
      },
      columns:[
        [{
          span:8,
          // label:'设备名称',
          labelWidth:1,
          prop:'searchText',
          component:'by-input',
          compConfig:{ 
            attr:{
              placeholder:'请输入区域名称',
              prefixIcon:'vxe-icon-search'
            }
          }
        }]
      ]
    },
    tool:{
      tools:{
        // export:true,
        add:true,
        delete:true,
        search:true,
        refresh:true
      },
      customTools:[{
        name: '导出', 
        icon: 'bottom',
        event:{
          click:() =>{
            loadDown()
          }
        }
      }]
    },
    table:{
      attr:{
        size:'mini',
        seq:true,
        align:'center',
        checkbox:true
      },
      columns:[
      {
        isDetail:true,
        title:'区域名称',
        field:'storeName',
      },
      {
        title:'地址',
        field:'addrCodeInfo'
      },
      {
        title:'联系人',
        field:'principalName'
      },
      {
        title:'联系人手机',
        field:'principalTelephone'
      },
      {
        title:'关联设备数量',
        field:'count'
      },
      {
        title:'操作',
        action:true,
        plugins:[{
          name:'设备查看',
          audit:'',
          event:{
            click:item => {
              showEquipModal(item)
            }
          }
        }]
      }
      ]
    },
    modal:{
      tool:{
        tools:{
          return:true,
          add:true
        }
      },
      form:{
        attr:{
          width:'1000px',
          size:'small',
          labelWidth:'130px',
          rules:{
            storeName:[
              {required: true, message: '请输入店铺名称', trigger: 'blur'}
            ],
            principalName:[
              {required: true, message: '请选择负责人', trigger: 'blur'},
            ],
            addrCode:[
              {required: true, message: '请选择位置', trigger: 'blur'}
            ],
            addrInfo:[
              {required: true, message: '请输入详细地址', trigger: 'blur'}
            ],
            principalTelephone:[
              {required: true, message: '请输入负责人电话', trigger: 'blur'},
              { validator: (rule, value, callback) => {
                if (value) {
                  if(!/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value)) {
                    callback(new Error('手机号格式不正确！'));
                  }else{
                    callback();
                  }
                } else {
                  callback();
                }
              }, trigger: 'blur' }
            ]
          }
        },
        columns:[
          [{
            label:'店铺名称',
            prop:'storeName',
            component:'by-input',
            compConfig:{
              attr:{}
            }
          }],
          [{
            label:'负责人',
            prop:'principalName',
            component:'by-input'
          },{
            label:'负责人电话',
            prop:'principalTelephone',
            component:'by-input'
          }],
          [{
            label:'位置',
            prop:'addrCode',
            component:'by-area',
            compConfig:{
              attr:{
                area:'addrCodeInfo',
                areaCode:'addrCode'
              }
            }
          }],
          [{
            label:'详细地址',
            prop:'addrInfo',
            component:shallowRef(address)
          }],
          [{
            label:'范围',
            prop:'point',
            component:shallowRef(mapRang),
          }],
          [{
            label:'标记',
            prop:'lnglat',
            component:'MapMaker',
            compConfig:{
              attr:{
                lng:'lng',
                lat:'lat'
              }
            }
          }]
        ]
      }
    }
  })
  const load = ref(false)
  const isSearch = ref(false)
  const timeNum = ref(0);

  //导出
  const loadDown = () => {
    let data = proxy.$refs.view.getQuery();
    data.pageNum = data.pageNo;
    delete data.pageNo;
    proxy.download('/store/export',data,`线下店铺_${new Date().getTime()}.xlsx`)
  }

  //店铺新增设备
  const addEquipHandle = row => {
    proxy.$refs.noAddEquipView.setShow(true);
    proxy.$refs.noAddEquipView.setValue(row);
  }

  //重新查看设备列表
  const addEquipCloseHandle = row => {
    showEquipModal(row)
  }

  const detail = () => {
    config.value.modal.tool.tools.save = true;
    delete config.value.modal.tool.tools.add;
    proxy.$refs.view.initFormTool();
  }

  //查看设备列表
  const showEquipModal = row => {
    proxy.$refs.equipModalView.setShow(true);
    proxy.$refs.equipModalView.setValue(row);
  } 

  const clickHandle = n => {
    if(n == 'onAdd'){
      config.value.modal.tool.tools.add = true;
      delete config.value.modal.tool.tools.save;
      proxy.$refs.view.initFormTool();
    }
    if(n == 'onDelete'){
      delHandle()
    }
  }
  const modalHandle = n =>{
    if(n == 'onAdd'){
      proxy.$refs.view.getFormValidate(addData)
    }

    if(n == 'onSave'){
      proxy.$refs.view.getFormValidate(onSave)
    }
  }
  const delHandle = () => {
    let data = proxy.$refs.view.getSelectData();
    let ids = []
    if(!data && data.lenght == 0) {
      proxy.$message('请选择数据')
      return
    }
    for(const item of data) {
      ids.push(item.storeId)
    }
    proxy.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      load.value = true;
      delShop({
        storeIds:ids,
      }).then(()=>{
        proxy.$message({message:'删除成功！',type:'success'})
        load.value = false;
        getList();
      }).catch(()=>{
        load.value = false;
      })
    }).catch(()=>{})
  }
  //添加
  const addData = () => {
    let value = proxy.$refs.view.getFormValue();
    if(value){
      load.value = true;
      addShop(value).then(res =>{
        load.value = false;
        proxy.$message({
          message:res.msg,
          type:'success'
        });
        proxy.$refs.view.closeModal();
        getList();
      }).catch(()=>{
        load.value = false;
      })
    }
  }
  //保存
  const onSave = () => {
    let data = proxy.$refs.view.getFormValue();
    load.value = true;
    updateShop(data).then(res => {
      proxy.$message({
        message:res.msg,
        type:'success'
      });
      load.value = false;
      proxy.$refs.view.closeModal();
      pagination();
    }).catch(() => {
      load.value = false;
    })
  }
  const pagination = () => {
    if(isSearch.value){
      queryList();
    }else{
      getList()
    }
  }
  //列表请求（包含分页和搜素条件）
  const queryList = () => {
    isSearch.value = true;
    let data = proxy.$refs.view.getQuery();
    requestList(data);
  }
  const getList = () => {
    if(!proxy.$refs.view){
      if(timeNum.value > 5){
        return
      }
      setTimeout(()=>{
        getList()
      },500) 
      timeNum.value ++;
      return
    }
    timeNum.value = 0;
    isSearch.value = false;
    let data = proxy.$refs.view.getPage();
    requestList(data);
  }
  const requestList = data => {
    load.value = true;
    data.pageNum = data.pageNo;
    delete data.pageNo;
    listShop(data).then(res => {
      load.value = false;
      proxy.$refs.view.setTableValue(res.data.data);
      let page = {
        pageNo: res.data.page.pageNum, //当前页
        pageSize: data.pageSize, //每页条数
        total: res.data.page.total //总条数
      };
      proxy.$refs.view.setPage(page)

    }).catch(()=>{
      load.value = false;
    })
  }
  const calculateTable = () => {
    nextTick(() => {
      proxy.$refs.view.initTable()
    })
  }
  defineExpose({
    calculateTable
  })
  
  nextTick(()=>{
    getList()
  })

</script>
