<template>
  <div class="divBox">
    <div class="selCard">
      <el-form
        :model="tableFrom"
        ref="searchForm"
        size="small"
        label-width="105px"
        :inline="true"
      >
        <el-form-item label="选择时间：">
          <el-date-picker
            v-model="timeVal"
            placeholder="选择日期"
            value-format="yyyy/MM/dd HH:mm:ss"
            format="yyyy/MM/dd HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            style="width: 280px"
            :picker-options="pickerOptions"
            @change="onchangeTime"
          />
        </el-form-item>
        <el-form-item label="商户类别：" prop="is_trader">
          <el-select
            v-model="tableFrom.is_trader"
            clearable
            placeholder="请选择"
            class="selWidth"
            @change="getList(1)"
          >
            <el-option label="自营" value="1" />
            <el-option label="非自营" value="0" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="是否惠美乡村：" prop="is_huimei">
          <el-select
            v-model="tableFrom.is_huimei"
            placeholder="请选择"
            class="filter-item selWidth"
            clearable
            @change="getList(1)"
          >
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否退伍军人：" prop="is_soldier">
          <el-select
            v-model="tableFrom.is_soldier"
            placeholder="请选择"
            class="filter-item selWidth"
            clearable
            @change="getList(1)"
          >
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属城市：" prop="city">
          <el-input
            v-model="tableFrom.city"
            @keyup.enter.native="getList(1)"
            placeholder="请输入所属城市"
            class="selWidth"
            clearable
          />
        </el-form-item>
        <el-form-item label="店铺类型：" prop="type_id">
          <el-select
            v-model="tableFrom.type_id"
            clearable
            placeholder="请选择"
            class="selWidth"
            @change="getList(1)"
          >
            <el-option
              v-for="item in storeType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否推荐：" prop="is_best">
          <el-select
            v-model="tableFrom.is_best"
            clearable
            placeholder="请选择"
            class="selWidth"
            @change="getList(1)"
          >
            <el-option key="1" label="是" value="1" />
            <el-option key="0" label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="企业关键字：" prop="company">
          <el-input
            v-model="tableFrom.company"
            @keyup.enter.native="getList(1)"
            placeholder="请输入店铺/企业名称关键字"
            class="selWidth"
            clearable
          />
        </el-form-item>
        <el-form-item label="姓名关键字：" prop="name">
          <el-input
            v-model="tableFrom.name"
            @keyup.enter.native="getList(1)"
            placeholder="请输入法人/对接人姓名"
            class="selWidth"
            clearable
          />
        </el-form-item>
        <el-form-item label="对接人电话:" prop="phone">
          <el-input
            v-model="tableFrom.phone"
            @keyup.enter.native="getList(1)"
            placeholder="请输入对接人电话"
            class="selWidth"
            clearable
          />
        </el-form-item>
        <el-form-item label="对接人身份证：" prop="id_card">
          <el-input
            v-model="tableFrom.id_card"
            @keyup.enter.native="getList(1)"
            placeholder="请输入对接人身份证"
            class="selWidth"
            clearable
          />
        </el-form-item>
        <!-- <el-form-item label="是否店长店：" prop="is_store_mgr">
          <el-select
            v-model="tableFrom.is_store_mgr"
            clearable
            placeholder="请选择"
            class="selWidth"
            @change="getList(1)"
          >
            <el-option key="1" label="是" value="1" />
            <el-option key="0" label="否" value="0" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否新商户：" prop="is_new">
          <el-select
            v-model="tableFrom.is_new"
            clearable
            placeholder="请选择"
            class="selWidth"
            @change="getList(1)"
          >
            <el-option key="1" label="是" value="1" />
            <el-option key="0" label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否签署：" prop="is_sign">
          <el-select
            v-model="tableFrom.is_sign"
            clearable
            placeholder="请选择"
            class="selWidth"
            @change="getList(1)"
          >
            <el-option key="1" label="是" value="1" />
            <el-option key="0" label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="mark">
          <el-input
            v-model="tableFrom.mark"
            @keyup.enter.native="getList(1)"
            placeholder="请输入备注"
            class="selWidth"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="getList(1)"
            >搜索</el-button
          >
          <el-button size="small" @click="searchReset()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card class="mt14">
      <div class="mb20">
        <el-tabs
          v-if="headeNum.length > 0"
          v-model="isStatus"
          @tab-click="getList(1), getHeadNum()"
        >
          <el-tab-pane
            v-for="(item, index) in headeNum"
            :key="index"
            :name="item.type.toString()"
            :label="item.title + '(' + item.count + ')'"
          />
        </el-tabs>
        <el-button size="small" type="primary" class="mt5" @click="onAdd"
          >添加商户</el-button
        >
        <el-button size="small" type="primary" class="mt5" @click="exports"
          >导出列表</el-button
        >
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        size="small"
        highlight-current-row
      >
        <el-table-column prop="mer_id" label="ID" min-width="60" />
        <el-table-column prop="mer_name" label="店铺名称" min-width="150" />
        <el-table-column prop="ext.com.name" label="企业名称" min-width="150" />
        <el-table-column
          prop="merchantType.type_name"
          label="店铺类型"
          min-width="150"
        />
        <!-- <el-table-column prop="is_huimei" label="是否惠美乡村" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.is_huimei == 1 ? "是" : "否" }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="is_soldier" label="是否军人" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.is_soldier == 1 ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_new" label="是否新商户" min-width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.is_new == 1 ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="is_store_mgr" label="是否店长店" min-width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.is_store_mgr == 1 ? "是" : "否" }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="is_sign" label="是否签署" min-width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.is_sign == 1 ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="ext.idcard.name"
          label="法人姓名"
          min-width="150"
        />
        <el-table-column prop="status" label="推荐" min-width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_best"
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
              :width="40"
              @click.native="onchangeIsShow(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="退店(开启/关闭)" min-width="120">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="0"
              :inactive-value="1"
              active-text="开启"
              inactive-text="关闭"
              :width="55"
              @click.native="onchangeIsClose(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="lock"
          label="限制(开启/关闭)"
          min-width="120"
          v-if="isStatus != 0"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.lock"
              :active-value="1"
              :inactive-value="0"
              active-text="开启"
              inactive-text="关闭"
              :width="55"
              @click.native="onchangeIsClose(scope.row, 'lock')"
            />
          </template>
        </el-table-column>
        <el-table-column prop="real_name" label="对接人姓名" min-width="100" />
        <el-table-column prop="mer_phone" label="对接人电话" min-width="100" />
        <el-table-column
          prop="ext.com.number"
          label="对接人身份证号"
          min-width="120"
        />
        <!-- <el-table-column prop="ext.com.initiator" label="发起人姓名" min-width="100" />
        <el-table-column prop="ext.com.inti_number" label="发起人编号" min-width="100" />
        <el-table-column prop="ext.com.inti_mobile" label="发起人电话" min-width="100" /> -->
        <el-table-column
          prop="ext.biz.cityInfo"
          label="所属城市"
          min-width="100"
        />
        <el-table-column prop="create_time" label="创建时间" min-width="150" />
        <el-table-column prop="margin" label="保证金" min-width="150">
          <template slot-scope="scope">
            <span>{{ getNumber(scope.row, "margin") }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="service" label="技术服务费" min-width="150">
          <template slot-scope="scope">
            <span>{{ getNumber(scope.row, "service") }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods" label="上架费" min-width="150">
          <template slot-scope="scope">
            <span>{{ getNumber(scope.row, "goods") }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" min-width="100" />
        <el-table-column prop="mark" label="备注" min-width="200" />

        <el-table-column label="操作" min-width="220" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="isStatus === '1' || isStatus === '2'"
              type="text"
              size="small"
              @click="onLogo(scope.row.mer_id)"
              >登录</el-button
            >
            <el-button
              v-if="isStatus === '1'"
              type="text"
              size="small"
              @click="handleSign(scope.row.mer_id)"
              >签署</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="onEdit(scope.row.mer_id)"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="setPayment(scope.row.mer_id)"
              >缴费</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="onDetails(scope.row.mer_id)"
              >详情</el-button
            >
            <el-button
              v-if="isStatus === '0'"
              type="text"
              size="small"
              @click="handleDelete(scope.row.mer_id, scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <!--商户详情-->
    <mer-detail
      ref="merDetail"
      :merId="merId"
      :merCateList="merCateList"
      :storeType="storeType"
      @closeDrawer="closeDrawer"
      @changeDrawer="changeDrawer"
      @onPassword="onPassword"
      @handleTimes="handleTimes"
      @getList="getList"
      :drawer="drawer"
    ></mer-detail>
  </div>
</template>
<script>
import {
  merchantListApi,
  merchantDeleteForm,
  merchantStatuseApi,
  merchantPasswordApi,
  merchantLoginApi,
  changeCopyApi,
  merchantCountApi,
  merchantIsCloseApi,
  merchantIsLockApi,
  getstoreTypeApi,
  merchantPayForm,
  exportMerchantApi,
  getMerCateApi,
  marginDeductionForm,
  merchantContactApi,
} from "@/api/merchant";
import merDetail from "./handle/merDetails.vue";
import { fromList } from "@/libs/constants.js";
import { roterPre } from "@/settings";
import SettingMer from "@/libs/settingMer";
import createWorkBook from "@/utils/newToExcel.js";
import Cookies from "js-cookie";
import timeOptions from "@/utils/timeOptions";
import cityOptions from "@/utils/city";
export default {
  name: "MerchantList",
  components: { merDetail },
  data() {
    return {
      fromList: fromList,
      pickerOptions: timeOptions,
      roterPre: roterPre,
      isChecked: false,
      listLoading: true,
      merCateList: [],
      cityOptions: cityOptions,
      storeType: [],
      headeNum: [
        {
          count: "",
          type: "1",
          title: "正常开启的商户",
        },
        {
          count: "",
          type: "2",
          title: "已限制商户",
        },
        {
          count: "",
          type: "0",
          title: "已退店商户",
        },
      ],
      tableData: {
        data: [],
        total: 0,
      },
      tableFrom: {
        page: 1,
        limit: 20,
        date: "",
        status: "1",
        company: "",
        is_trader: "",
        is_best: "",
        category_id: "",
        is_sign: "",
        type_id: "",
        city: "",
        phone: "",
        name: "",
        mark: "",
        is_new: "",
      },
      isStatus: "1",
      autoUpdate: true,
      merId: "",
      drawer: false,
      timeVal: [],
    };
  },
  mounted() {
    this.getHeadNum();
    this.getMerCategory();
    this.getStoreType();
    this.getList("");
  },
  methods: {
    getNumber(row, name) {
      if (name == "margin") {
        return row[`is_${name}`] == 0
          ? "无"
          : row[`ot_${name}`] - row[`${name}`] > 0
          ? "待缴"
          : "已缴";
      } else {
        return row[`is_${name}`] == 0
          ? "无"
          : row[`ot_${name}_cost`] - row[`${name}_cost`] > 0
          ? "待缴"
          : "已缴";
      }
    },
    handleCascader() {
      this.tableFrom.city = this.$refs["cascader"]?.getCheckedNodes()[0]?.label;
      this.getList(1);
    },
    async exports() {
      let excelData = JSON.parse(JSON.stringify(this.tableFrom)),
        data = [];
      excelData.page = 1;
      excelData.limit = 100;
      let pageCount = 1;
      let lebData = {};
      for (let i = 0; i < pageCount; i++) {
        lebData = await this.downData(excelData);
        pageCount = Math.ceil(lebData.count / excelData.limit);
        if (lebData.export.length) {
          data = data.concat(lebData.export);
          excelData.page++;
        }
      }
      createWorkBook(
        lebData.header,
        lebData.title,
        data,
        lebData.foot,
        lebData.filename
      );
      return;
    },
    /**订单列表 */
    downData(excelData) {
      return new Promise((resolve, reject) => {
        exportMerchantApi(excelData).then((res) => {
          return resolve(res.data);
        });
      });
    },
    /**重置 */
    searchReset() {
      this.timeVal = [];
      this.tableFrom.date = "";
      this.$refs.searchForm.resetFields();
      this.getList(1);
    },
    // 签署
    handleSign(id) {
      merchantContactApi(id)
        .then((res) => {
          this.$message.success(res.message);
          window.open(res.message);
        })
        .catch((res) => {
          this.$message.error(res.message);
        });
    },
    onLogo(id) {
      merchantLoginApi(id)
        .then((res) => {
          Cookies.set("merchantToken", res.data.token);
          window.open(`${location.origin}${res.data.url}`);
        })
        .catch((res) => {
          this.$message.error(res.message);
        });
    },
    // 具体日期
    onchangeTime(e) {
      this.timeVal = e;
      this.tableFrom.date = this.timeVal ? this.timeVal.join("-") : "";
      this.tableFrom.page = 1;
      this.getList("");
    },
    // 获取开启商户数
    getHeadNum() {
      merchantCountApi()
        .then((res) => {
          this.headeNum[0]["count"] = res.data.valid;
          this.headeNum[1]["count"] = res.data.lock;
          this.headeNum[2]["count"] = res.data.invalid;
        })
        .catch((res) => {});
    },
    // 商户分类；
    getMerCategory() {
      getMerCateApi()
        .then((res) => {
          this.merCateList = res.data;
        })
        .catch((res) => {
          this.$message.error(res.message);
        });
    },
    getStoreType() {
      getstoreTypeApi()
        .then((res) => {
          this.storeType = res.data;
        })
        .catch((res) => {
          this.$message.error(res.message);
        });
    },
    // 列表
    getList(num) {
      this.listLoading = true;
      if (this.isStatus == 2) {
        this.tableFrom = { ...this.tableFrom, lock: "1", status: "" };
      } else {
        this.tableFrom = {
          ...this.tableFrom,
          status: this.isStatus,
          lock: "0",
        };
      }
      this.tableFrom.page = num ? num : this.tableFrom.page;
      merchantListApi(this.tableFrom)
        .then((res) => {
          this.tableData.data = res.data.list;
          this.tableData.total = res.data.count;
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
          this.$message.error(res.message);
        });
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList("");
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList(1);
    },
    // 修改状态
    onchangeIsShow(row) {
      const title = row.is_best === 1 ? "是否开启推荐商户" : "是否关闭推荐商户";
      this.$modalSure(title).then(() => {
        merchantStatuseApi(row.mer_id, row.is_best)
          .then(({ message }) => {
            this.$message.success(message);
            this.getList("");
          })
          .catch(({ message }) => {
            this.getList("");
            this.$message.error(message);
          });
      });
    },
    // 开启关闭退店
    onchangeIsClose(row, type) {
      type == "lock"
        ? merchantIsLockApi(row.mer_id, row.lock)
            .then(({ message }) => {
              this.$message.success(message);
              this.getList("");
              this.getHeadNum();
            })
            .catch(({ message }) => {
              this.$message.error(message);
            })
        : merchantIsCloseApi(row.mer_id, row.status)
            .then(({ message }) => {
              this.$message.success(message);
              this.getList("");
              this.getHeadNum();
            })
            .catch(({ message }) => {
              this.$message.error(message);
            });
    },
    // 添加
    onAdd() {
      // this.$modalForm(merchantCreateApi()).then(() => this.getList(""));
      this.drawer = true;
      this.$refs.merDetail.initData();
    },
    // 编辑
    onEdit(id) {
      this.merId = id;
      this.$refs.merDetail.isEdit = true;
      this.$refs.merDetail.getInfo(id);
      this.drawer = true;
    },
    // 详情
    onDetails(id) {
      this.merId = id;
      this.$refs.merDetail.isEdit = false;
      this.$refs.merDetail.getInfo(id);
      this.drawer = true;
    },
    changeDrawer(v) {
      this.drawer = v;
    },
    closeDrawer() {
      this.drawer = false;
    },
    // 缴费
    setPayment(id) {
      this.$modalForm(merchantPayForm(id)).then(() => this.getList(""));
    },
    // 删除
    handleDelete(id) {
      this.$modalForm(merchantDeleteForm(id)).then(() => this.getList(""));
    },
    // 扣除保证金
    onDeduct(id) {
      this.$modalForm(marginDeductionForm(id)).then(() => this.getList(""));
    },
    // 设置复制次数
    handleTimes(id) {
      this.$modalForm(changeCopyApi(id)).then(() => this.getList(""));
    },

    // 修改密码表单
    onPassword(id) {
      this.$modalForm(merchantPasswordApi(id));
    },
  },
};
</script>

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