<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" 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="businessCategoryId">
        <el-select v-model="queryParams.businessCategoryId" placeholder="请选择商家分类" clearable style="width: 240px">
          <el-option v-for="(v, i) in shopTypeList" :key="i" :label="v.name" :value="v.categoryId" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="营业状态" prop="businessStatus">
        <el-select v-model="queryParams.businessStatus" placeholder="请选择营业状态" clearable style="width: 240px">
          <el-option label="正常" :value="true" />
          <el-option label="停业" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="商家分类" prop="businessCategoryId">
        <el-select v-model="queryParams.businessCategoryId" placeholder="请选择商家分类" clearable style="width: 240px">
          <el-option v-for="(v, i) in shopTypeList" :key="i" :label="v.name" :value="v.categoryId" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="推荐状态" prop="hotStatus">
        <el-select v-model="queryParams.hotStatus" placeholder="请输入热门状态" clearable style="width: 240px">
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态" prop="shelvedStatus">
        <el-select v-model="queryParams.shelvedStatus" placeholder="请输入状态" clearable style="width: 240px">
          <el-option label="上架" :value="true" />
          <el-option label="下架" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="所在城市" prop="provinces">
        <el-cascader ref="refSubCat" v-model="queryParams.provinces" placeholder="请选择所在城市" :options="areaTrea"
          :props="{ expandTrigger: 'hover' }" @change="handleChange" style="width: 100%"></el-cascader>
      </el-form-item> -->
      <!-- <el-form-item label="城市合伙人" prop="cityPartnerId">
        <el-select v-model="queryParams.cityPartnerId" placeholder="请选择" filterable clearable  style="width: 240px">
          <el-option v-for="(v,i) in partnerList" :key="i" :label="v.username" :value="v.partnerId" />
        </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">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus"  @click="handleAdd">新增</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :size="ELTableSize" :data="list" @selection-change="handleSelectionChange"
      @sort-change="sortChange">
      <el-table-column type="index" width="55" label="序号" align="center">
        <template slot-scope="scope">
          <div>
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="店铺ID" align="center" prop="businessId" width="100" />
      <el-table-column label="店铺信息" align="center" prop="businessName">
        <template slot-scope="{row}">
          <div>
            <p>店铺名称：{{ row.businessName }}</p>
            <p>店铺所在区域：{{ row.provinceName + row.cityName + row.areaName }}</p>
            <p>店铺地址：{{ row.address }}</p>
            <p>客服电话：{{ row.customerServicePhone }}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="主体信息" align="center" prop="enterpriseName">
        <template slot-scope="{row}">
          <div>
            <p>企业名称：{{ row.enterpriseName }}</p>
            <p>统一信用代码：{{ row.uscCode }}</p>
            <p>法人姓名：{{ row.legalName }}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="资金余额" align="center" prop="balance" />
      <el-table-column label="店铺积分" align="center" prop="totalIntegral" />

      <el-table-column label="审核通过时间" align="center" prop="createTime" />


      <el-table-column label="营业状态" align="center" prop="businessStatus">
        <template slot-scope="{row}">
          <el-tag type="success" v-if="row.businessStatus">正常</el-tag>
          <el-tag type="danger" v-if="!row.businessStatus">停业</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="text" :size="ELTableSize" @click="handleUpdate(scope.row)">修改</el-button>
          <el-dropdown :size="ELTableSize" 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(scope.row)">删除</el-dropdown-item>
              <el-dropdown-item @click.native="setStatus(scope.row)">{{ scope.row.shelvedStatus ? '下架' : '上架'
              }}</el-dropdown-item>
              <el-dropdown-item @click.native="$refs.businessDataRef.openHandle(scope.row)">经营明细</el-dropdown-item>
              <el-dropdown-item @click.native="$refs.payConfigRef.openHandle(scope.row)">支付配置</el-dropdown-item>
              <el-dropdown-item @click.native="openSystemUser(scope.row)">{{ scope.row.businessUser &&
                scope.row.businessUser.userId ? '修改商家管理员' : '新增商家管理员' }}</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.businessUser && scope.row.businessUser.userId"
                @click.native="handleResetPwd(scope.row.businessUser)">重置商家管理员密码</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" />
  </div>
</template>

<script>
import { businessPage, businessStatus, businessDel, businessCategoryList, cnAreaTree, systemUserResetPwd } from "@/api/shop.js";
// import { partnerRelationList } from "@/api/partner"
import systemUser from "./systemUser.vue"
import PayConfig from "@/views/shop/components/PayConfig.vue";
import BusinessData from "@/views/shop/components/BusinessData.vue";

export default {
  components: {
    systemUser,
    PayConfig,
    BusinessData
  },
  data() {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试单表表格数据
      list: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        businessId: undefined,
        businessName: undefined,
        contactPerson: undefined,
        provinces: undefined,
        businessStatus: undefined,
        shelvedStatus: undefined,
        businessCategoryId: undefined,
        hotStatus: undefined,
        cityPartnerId: undefined
      },
      daterangeCreateTime: [],
      areaTrea: [],
      shopTypeList: [],
      partnerList: []
    }
  },
  created() {
    if (this.$route.query.parentId) {
      this.queryParams.cityPartnerId = this.$route.query.parentId * 1
    }
    this.getShopTypeList()
    this.getCnAreaTree();
    // this.getPartnerList()
    this.getList()
  },
  methods: {
    handlePayConfig(row) {
      console.log(row)
    },

    openSystemUser(row) {
      this.$refs.systemUserRef.open(row)
    },
    getPartnerList() {
      partnerRelationList().then(res => {
        this.partnerList = res.data
      })
    },
    /** 重置密码按钮操作 */
    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(() => { });
    },
    sortChange(e) {
      this.queryParams.orderByColumn = 'order_index';
      this.queryParams.isAsc = e.order;
      this.handleQuery()
    },
    /** 查询测试单表列表 */
    getList() {
      this.loading = true;
      this.queryParams["startTime"] = undefined;
      this.queryParams["endTime"] = undefined;
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams["startTime"] = this.daterangeCreateTime[0];
        this.queryParams["endTime"] = this.daterangeCreateTime[1];
      }
      businessPage(this.queryParams).then(response => {
        // response.rows.map(v => {
        //   let arr = []
        //   v.businessCategoryList.map(k => {
        //     arr.push(k.categoryName)
        //   })
        //   v.categoryNames = arr.join(",")
        // })
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCnAreaTree() {
      cnAreaTree().then(res => {
        this.areaTrea = res.data?.children
      })
    },
    // 省市区选择
    handleChange(value) {
      this.queryParams.provinces = value;
      this.queryParams.provinceCode = value[0];
      this.queryParams.provinceName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[0];
      this.queryParams.cityCode = value[1];
      this.queryParams.cityName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[1];
      this.queryParams.areaCode = value[2];
      this.queryParams.areaName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[2];
    },
    getShopTypeList() {
      businessCategoryList().then(res => {
        this.shopTypeList = res.data
      })
    },
    handleAdd() {
      this.$router.push({
        path: '/shop/details'
      })
    },
    handleUpdate(row) {
      this.$router.push({
        path: '/shop/details',
        query: {
          businessId: row.businessId
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        shelvedStatus: undefined,
        orderIndex: 1
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.queryParams.provinceCode = undefined;
      this.queryParams.provinceName = undefined;
      this.queryParams.cityCode = undefined;
      this.queryParams.cityName = undefined;
      this.queryParams.areaCode = undefined;
      this.queryParams.areaName = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.businessId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.businessId || this.ids;
      this.$modal.confirm('是否确认删除商家名称为"' + row.businessName + '"的数据项？').then(() => {
        this.loading = true;
        return businessDel(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 上下架按钮操作 */
    setStatus(row) {
      const ids = row.businessId || this.ids;
      let statusText = row.shelvedStatus ? '下架' : '上架';
      this.$modal.confirm('是否确认' + statusText + '商家名称为"' + row.businessName + '"的数据项？').then(() => {
        this.loading = true;
        return businessStatus(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess(statusText + "成功");
      }).finally(() => {
        this.loading = false;
      });
    },
  }
}
</script>

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