<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="店铺名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入店铺名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择店铺状态" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.store_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否生效" prop="enabled">
        <el-select v-model="queryParams.enabled" placeholder="请选择审核状态" clearable  @change="handleQuery">
          <el-option label="已生效" :value="true"/>
          <el-option label="未生效" :value="false"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @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"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange">
      <el-table-column type="index" width="55" align="center" label="#" />
      <el-table-column label="店铺名称" align="center" prop="name" min-width="100">
        <store-link slot-scope="d" :id="d.row.storeId" :name="d.row.name"/>
      </el-table-column>
      <el-table-column label="店铺类型" align="center" prop="type" width="100">
        <template slot-scope="scope">
          <dict-tag :value="scope.row.type" :options="dict.type.ss_store_type"/>
        </template>
      </el-table-column>
      <el-table-column label="店铺图片" align="center" prop="picture" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.picture" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="营业时间" align="center" min-width="100">
        <template slot-scope="d">
          {{d.row.businessTimeStart}} 至 {{d.row.businessTimeEnd}}
        </template>
      </el-table-column>
      <el-table-column label="门店地址" align="center" min-width="200">
        <template slot-scope="d">
          {{d.row.province}}{{d.row.city}}{{d.row.county}}{{d.row.address}}
        </template>
      </el-table-column>
      <el-table-column label="店铺状态" align="center">
        <template slot-scope="d">
          <dict-tag :value="d.row.status" :options="dict.type.store_status"/>
        </template>
      </el-table-column>
      <el-table-column label="是否生效" align="center">
        <template slot-scope="d">
          <el-tag :type="d.row.enabled ? 'success' : 'danger'">{{d.row.enabled ? '已生效' : '未生效'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设备数量" align="center">
        <template slot-scope="d">{{d.row.deviceCount}} 台</template>
      </el-table-column>
      <el-table-column label="在线数量" align="center">
        <template slot-scope="d">{{d.row.onlineCount}} 台</template>
      </el-table-column>
      <el-table-column label="离线数量" align="center">
        <template slot-scope="d">{{d.row.offlineCount}} 台</template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改店铺列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="8">
          <form-col label="店铺图片" prop="picture" :span="span * 2">
            <image-upload v-model="form.picture" :limit="9"/>
          </form-col>
          <form-col label="店铺名称" prop="name" :span="span">
            <el-input v-model="form.name" placeholder="请输入店铺名称" />
          </form-col>
          <form-col label="店铺类型" prop="type" :span="span">
            <el-select v-model="form.type" placeholder="请选择店铺类型" style="width: 100%">
              <el-option
                v-for="opt of dict.type.ss_store_type"
                :label="opt.label"
                :key="opt.value"
                :value="opt.value"
              />
            </el-select>
          </form-col>
          <form-col label="营业时间" prop="businessTimeStart" :span="span">
            <el-time-picker
              is-range
              v-model="formatBusinessTime"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              :clearable="false"
              style="width: 100%"
              placeholder="请选择营业时间范围">
            </el-time-picker>
          </form-col>
          <form-col label="是否在地图展示" prop="show" :span="span" label-width="9em">
            <el-switch v-model="form.show"/>
          </form-col>
          <form-col label="定位地址" prop="address" :span="span * 2">
            <el-input v-model="form.address" placeholder="请输入店铺地址">
              <template #prepend>
                <div>
                  {{form.province}}{{form.city}}{{form.county}}
                </div>
              </template>
              <template #append>
                <el-button @click="showPlaceSearchMap = true" icon="el-icon-location">选择定位</el-button>
              </template>
            </el-input>
          </form-col>
          <form-col label="联系人" prop="contactName" :span="span">
            <el-input v-model="form.contactName" placeholder="请输入联系人"/>
          </form-col>
          <form-col label="联系电话" prop="contactMobile" :span="span">
            <el-input v-model="form.contactMobile" placeholder="请输入联系电话" maxlength="11" show-word-limit/>
          </form-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <place-search-dialog
      :show.sync="showPlaceSearchMap"
      :init-lat="form.lat"
      :init-lng="form.lng"
      @submit="onSubmitAddress"
      marker-type="store"
    />

  </div>
</template>

<script>
import UserInput from '@/components/Business/SmUser/UserInput.vue'
import PlaceSearchDialog from '@/components/Map/PlaceSearch/PlaceSearchDialog.vue'
import AreaTextSelect from '@/components/AreaTextSelect/index.vue'
import { parseTime } from '@/utils/ruoyi'
import { $view } from '@/utils/mixins'
import UserLink from '@/components/Business/SmUser/UserLink.vue'
import StoreLink from '@/components/Business/Store/StoreLink.vue'
import { mchAddStore, mchCancelStore, mchDelStore, mchGetStore, mchListStore, mchUpdateStore } from '@/api/mch/store'
import MchStoreApplyDetail from '@/views/mch/storeApply/detail.vue'

export default {
  name: "MyStore",
  mixins: [$view],
  dicts: ['ss_store_type', 'store_status'],
  components: { MchStoreApplyDetail, StoreLink, UserLink, AreaTextSelect, PlaceSearchDialog, UserInput },
  props: {
    query: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 店铺列表表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        storeId: null,
        userId: null,
        name: null,
        address: null,
        deleted: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "店铺名称不能为空", trigger: "change" }
        ],
        address: [
          { required: true, message: "定位地址不能为空", trigger: "change" }
        ],
        type: [
          { required: true, message: "店铺类型不能为空", trigger: "change" }
        ],
        businessTimeStart: [
          { required: true, message: "营业时间不允许为空", trigger: "change" }
        ],
        contactName: [
          { required: true, message: "联系人不允许为空", trigger: "change" }
        ],
        contactMobile: [
          { required: true, message: "联系电话不允许为空", trigger: "change" }
        ],
      },
      showPlaceSearchMap: false,
      span: 12,
    };
  },
  computed: {
    formatBusinessTime: {
      set(val) {
        this.form.businessTimeStart = val[0];
        this.form.businessTimeEnd = val[1];
      },
      get() {
        if (this.form.businessTimeStart == null || this.form.businessTimeEnd == null) {
          return null;
        }
        return [this.form.businessTimeStart, this.form.businessTimeEnd]
      }
    }
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }
    this.getList();
  },
  methods: {
    parseTime,
    onSubmitAddress(addr) {
      this.form.address = addr.name;
      this.form.lat = addr.lat;
      this.form.lng = addr.lng;
      this.form.province = addr.province;
      this.form.city = addr.city;
      this.form.county = addr.county;
      this.form.specificAddress = addr.name;
    },
    /** 查询店铺列表列表 */
    getList() {
      this.loading = true;
      mchListStore(this.queryParams).then(response => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        storeId: null,
        userId: this.query.userId,
        picture: null,
        name: null,
        address: null,
        specificAddress: null,
        businessTimeStart: "08:00",
        businessTimeEnd: "18:00",
        province: "福建省",
        city: "宁德市",
        county: "福鼎市",
        lng: null,
        lat: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        deleted: null,
        show: true
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.storeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加店铺列表";
    },
    handleView(row) {
      this.$router.push({
        path: `/business/store/${row.storeId}`,
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const storeId = row.storeId || this.ids
      mchGetStore(storeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改店铺列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.storeId != null) {
            mchUpdateStore(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            mchAddStore(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log("store", row);
      this.$modal.confirm(`是否确认删除店铺 “${row.name}” ？`).then(function() {
        return mchDelStore(row.storeId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ss/store/export', {
        ...this.queryParams
      }, `store_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
