<template>
  <div class="page-box">
    <moduleView :propConfig="config" ref="view" v-loading="load" @pagination="pagination" @onRefresh="getList" @resert="queryList" @search="queryList" @modalHandle="modalHandle" @clickHandle="clickHandle" @detail="detail" />
  </div>
</template>

<script setup>
  import { computed,getCurrentInstance,ref  } from "vue";
  const { proxy } = getCurrentInstance();
  import {list,del,add,update} from '@/api/base/merchantManage'
  import upload from "./components/upload.vue";
  import tableImg from "./components/tableImg.vue";
  import stateRadio from "./components/stateRadio.vue";

  const config = ref({
    attr:{
      calculateH:true
    },
    search:{
      attr:{
        size:'mini',
        rules:{
          name:[{
            required: true, message: '请输入名称', trigger: 'blur'
          }]
        }
      },
      columns:[
        [{
          span:8,
          // label:'设备名称',
          labelWidth:16,
          prop:'searchText',
          component:'by-input',
          compConfig:{ 
            attr:{
              placeholder:'请输入商户名称、联系人、联系方式',
              prefixIcon:'vxe-icon-search'
            }
          }
        }]
      ]
    },
    tool:{
      tools:{
        export:true,
        add:true,
        // delete:true,
        search:true,
        refresh:true
      }
    },
    table:{
      attr:{
        size:'mini',
        seq:true,
        align:'center',
        // checkbox:true
      },
      columns:[
      // {
      //   title:'商户ID',
      //   field:'commercialId',
      // },
      {
        isDetail:true,
        title:'商户名称',
        field:'commercialName',
      },
      {
        title:'营业执照',
        field:'prove1',
        component:shallowRef(tableImg)
      },
      {
        title:'状态',
        field:'state',
        component:'textChange',
        compConfig:{
          attr:{
            data:[{
              label:'启用',
              value:1,
              backgroundColor:'#f0f9eb',
              color:'#67c23a'
            },{
              label:'禁用',
              value:0,
              backgroundColor:'#fef0f0',
              color:'#f56c6c'
            }]
          }
        }
      },
      {
        title:'关联小程序',
        field:'apps',
        formatField: row => {
          let n = ''
          if(row.apps && row.apps.length > 0){
            for(const item of row.apps){
              n = n ? n + ',' + item : item
            }
          }
          return n;
        }
      },
      {
        title:'联系人',
        field:'principalName'
      },
      {
        title:'联系人手机',
        field:'principalTelephone'
      },
      {
        title:'地址',
        field:'addrCodeInfo'
      },
      {
        title:'社会统一信用代码',
        field:'code'
      },
      {
        title:'创建时间',
        field:'createTime'
      }]
    },
    modal:{
      tool:{
        tools:{
          return:true,
          add:true
        }
      },
      form:{
        attr:{
          width:'1000px',
          size:'small',
          labelWidth:'130px',
          rules:{
            commercialName:[
              {required: true, message: '请输入商户名称', trigger: 'blur'}
            ],
            code:[
              {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:'commercialName',
            component:'by-input',
            compConfig:{
              attr:{}
            }
          }],
          [{
            label:'营业执照',
            prop:'prove1',
            component:shallowRef(upload)
          }],
          [{
            label:'状态',
            prop:'state',
            component:shallowRef(stateRadio)
          }],
          [{
            label:'统一信用代码',
            prop:'code',
            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:'by-input'
          }]
        ]
      }
    }
  })
  const load = ref(false)
  const isSearch = ref(false)
  const timeNum = ref(0);

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

  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.equipmentId)
    }
    proxy.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      load.value = true;
      del({
        commercialIds: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;
      add(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;
    update(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;
    list(data).then(res => {
      load.value = false;
      proxy.$refs.view.setTableValue(res.data.data);
      let page = {
        pageNo: res.data.page.current, //当前页
        pageSize: data.pageSize, //每页条数
        total: res.data.page.total //总条数
      };
      proxy.$refs.view.setPage(page)

    }).catch(()=>{
      load.value = false;
    })
  }
  nextTick(()=>{
    getList()
  })
</script>

<style lang="scss" scoped>

</style>