<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" :size="ELsize" label-width="auto">

      <el-form-item label="店铺ID" prop="businessId">
        <el-input v-model="queryParams.businessId" @input="e => queryParams.businessId = $numberFilter(e)"
          placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商家名称" prop="businessName">
        <el-input v-model="queryParams.businessName" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="法人姓名" prop="legalName">
        <el-input v-model="queryParams.legalName" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="店铺类型" prop="businessType">
        <el-select v-model="queryParams.businessType" placeholder="请选择" clearable>
          <el-option v-for="(v, i) in ShopTypeOption" :key="i" :label="v.label" :value="v.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery('queryForm')">重置</el-button>
      </el-form-item>
    </el-form>



    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" :size="ELsize" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :border="TableBorder" :size="ELTableSize" v-loading="loading" :data="dataList">
      <el-table-column type="index" width="55" label="序号" align="center">
        <template slot-scope="{$index}">
          {{ $getTableIndex(queryParams, $index + 1) }}
        </template>
      </el-table-column>
      <el-table-column label="店铺ID" align="center" prop="businessId" width="100">
        <template slot-scope="{row}">
          {{ row.businessId | TableItemEmpty }}
        </template>
      </el-table-column>
      <el-table-column label="店铺信息" align="center" prop="businessName">
        <template slot-scope="{row}">
          <div>
            <p class="table-p">店铺名称：{{ row.businessName | TableItemEmpty }}</p>
            <p class="table-p">店铺所在区域：{{ joint(row, ['provinceName', 'cityName', 'areaName']) | TableItemEmpty }}</p>
            <p class="table-p">店铺地址：{{ row.address }}</p>
            <p class="table-p">客服电话：{{ row.customerServicePhone }}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="主体信息" align="center" prop="enterpriseName">
        <template slot-scope="{row}">
          <div>
            <p class="table-p">企业名称：{{ row.enterpriseName }}</p>
            <p class="table-p">统一信用代码：{{ row.uscCode }}</p>
            <p class="table-p">法人姓名：{{ row.legalName }}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="店铺积分" align="center" width="120">
        <template slot-scope="{row}">
          {{ row.totalIntegral | TableItemEmpty }}
        </template>
      </el-table-column>
      <el-table-column label="店铺类型" align="center" width="150">
        <template slot-scope="{row}">
          {{ row.businessType | ShopTypeOptionFilter | TableItemEmpty }}
        </template>
      </el-table-column>

      <el-table-column label="审核通过时间" align="center" width="180">
        <template slot-scope="{row}">
          {{ row.createTime | TableItemEmpty }}
        </template>
      </el-table-column>


      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="{row}">
          <StatusTag :status-vo="row.closeStatus | ShopStatusOptionFilter(true)" />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="170">
        <template slot-scope="{row}">
          <el-button type="text" :size="ELTableSize" @click="handleUpdate(row)">修改</el-button>
          <el-button type="text" :size="ELTableSize" @click="handleSetCategory(row)">设置分类</el-button>
          <el-dropdown style="margin-left: 5px;">
            <el-button type="text" :size="ELTableSize">更多<i class="el-icon-arrow-down" /></el-button>
            <!-- <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span> -->
            <el-dropdown-menu slot="dropdown">
              <!-- <el-dropdown-item @click.native="handleDelete(row)">删除</el-dropdown-item> -->
              <!-- <el-dropdown-item
                @click.native="$downloadImage(row.qrCode, row.businessName + '店铺码')">下载店铺码</el-dropdown-item> -->
              <el-dropdown-item @click.native="$refs.businessDataRef.openHandle(row)">经营明细</el-dropdown-item>

              <!-- 数据迁移：仅连锁店可操作。普通独立店铺无此功能。 -->
              <!-- 店铺关闭。 一旦关闭后，无法恢复。只有关闭店铺后才能做排队订单迁移 -->
              <template v-if="row.closeStatus === ShopStatusEnum.SHOP_NORMAL">
                <el-dropdown-item @click.native="$refs.payConfigRef.openHandle(row)">支付配置</el-dropdown-item>
                <el-dropdown-item @click.native="openSystemUser(row)">{{ row.businessUser &&
                  row.businessUser.userId ? '修改商家管理员' : '新增商家管理员' }}</el-dropdown-item>
                <el-dropdown-item v-if="row.businessUser && row.businessUser.userId"
                  @click.native="handleResetPwd(row.businessUser)">重置商家管理员密码</el-dropdown-item>
                <!-- <el-dropdown-item
                  @click.native="$refs.queueImportRef.openHandle(row, row.businessName + '导入排队订单')">排队导入</el-dropdown-item> -->
                <el-dropdown-item @click.native="closeShop(row)">店铺关闭</el-dropdown-item>
              </template>
              <!-- 只有关闭的连锁店才允许数据迁移 -->
              <!-- <el-dropdown-item
                v-else-if="[ShopTypeEnum.BRANCH_OFFICE, ShopTypeEnum.HEAD_OFFICE].includes(row.businessType)"
                @click.native="$refs.queueOrderRef.openHandle(row)">数据迁移</el-dropdown-item> -->

            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <systemUser ref="systemUserRef" @success="getList" />

    <!-- 支付配置 -->
    <PayConfig ref="payConfigRef" />
    <!-- 经营数据 -->
    <BusinessData ref="businessDataRef" />
    
    <!-- 排队订单 -->
    <!-- <QueueOrder ref="queueOrderRef" /> -->
    <!-- 排队导入 -->
    <!-- <QueueImport ref="queueImportRef" :ImportApi="importSubsidyQueueApi" @refresh="getList" /> -->

    <SetCategory ref="setCategoryRef" @success="getList" />
  </div>
</template>

<script>
import { businessPage, closeBusinessApi, businessDel, systemUserResetPwd, exportBusinessApi } from "@/api/shop.js";
import systemUser from "./systemUser.vue"
import PayConfig from "@/views/shop/components/PayConfig.vue";
import BusinessData from "@/views/shop/components/BusinessData.vue";
import QueueOrder from "@/views/shop/components/QueueOrder.vue";
import QueueImport from "@/components/FileImport/index.vue";

import getListApi from "@/mixins/getListApi";
import { ShopTypeOption, ShopTypeEnum, ShopStatusEnum } from "@/utils/statusEnum.js";
import { importSubsidyQueueApi } from "@/api/shop";
import SetCategory from "@/views/shop/components/SetCategory.vue";

export default {
  mixins: [getListApi],
  components: {
    systemUser,
    PayConfig,
    BusinessData,
    QueueOrder,
    QueueImport,
    SetCategory
  },
  data() {
    return {
      importSubsidyQueueApi,
      ShopTypeEnum,
      ShopTypeOption,
      ShopStatusEnum,
      listURL: businessPage,
      queryParams: {
        businessId: undefined,
        businessName: undefined,
        legalName: undefined,
        businessType: undefined,
      },
      exportObj: {
        url: exportBusinessApi,
        name: '商家列表'
      }
    }
  },
  created() {
    // if (this.$route.query.parentId) {
    //   this.queryParams.cityPartnerId = this.$route.query.parentId * 1
    // }  
    // // this.getPartnerList()
    // this.getList()
  },
  methods: {
    joint(row, fields) {
      let str = ''
      fields.forEach(field => {
        str += row[field] || ''
      })
      return str
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.businessId || this.ids;
      const businessName = row.businessName || '';
      this.$MessageBoxConfirm({
        text: `是否删除${businessName}店铺？`, confirmCallback: async (callback) => {
          try {
            await businessDel(ids);
            this.$successMsg(`删除${businessName}店铺成功`);
            this.getList();
          } catch { } finally {
            callback && callback();
          }
        }
      });
    },

    /** 上下架按钮操作 */
    closeShop(row) {
      const { businessId, businessName, closeStatus } = row || {};
      const statusText = closeStatus ? '开启' : '关闭';
      this.$MessageBoxConfirm({
        text: `是否${statusText}${businessName}店铺？`, confirmCallback: async (callback) => {
          try {
            await closeBusinessApi(businessId);
            this.$successMsg(`${statusText}${businessName}店铺成功`);
            this.getList();
          } catch ({ message }) {
            console.log('下架失败', message);
          } finally {
            callback && callback();
          }
        }
      });
    },

    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(({ value }) => {
        systemUserResetPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => { });
    },


    openSystemUser(row) {
      this.$refs.systemUserRef.open(row)
    },
    handleUpdate(row) {
      this.$router.push({
        path: '/shop/details',
        query: {
          businessId: row.businessId
        }
      })
    },




    // ------------------------------------



    handleAdd() {
      this.$router.push({
        path: '/shop/details'
      })
    },
    handleSetCategory(row) {
      this.$refs.setCategoryRef.open(row)
    }
  }
}
</script>

<style lang='scss' scoped></style>