<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="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入店铺名称"
          clearable
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入商户名称"
          clearable
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系电话"
          clearable
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入地址"
          clearable
          @input="handleQuery"
        />
      </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"
          v-has-permi="['bst:store:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-has-permi="['bst:store:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-has-permi="['bst:store:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange" :default-sort="defaultSort"  @sort-change="onSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="店铺ID" align="center" prop="storeId"/>
      <el-table-column label="店铺名称" align="center" prop="storeName">
        <template slot-scope="{row}">
          <div v-if="row.storeName != null">
            <i class="el-icon-takeaway-box"/>
            <store-link
              :id="row.storeId"
              :name="row.storeName || '--'"
              size="mini"
            />
          </div>
        </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" 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" prop="userName"/>
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="营业时间" align="center">
        <template #default="scope">
          {{ scope.row.startTime }} —— {{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleSee(scope.row)"
            v-has-permi="['bst:store:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-has-permi="['bst:store:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-has-permi="['bst:store:remove']"
          >删除</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="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <form-col :span="span"  label="店铺名称" prop="storeName">
            <el-input v-model="form.storeName" placeholder="请输入店铺名称" />
          </form-col>
          <form-col label="所属用户" prop="userId" :span="span">
            <user-input v-model="form.userId" :text.sync="form.userName" />
          </form-col>
          <form-col :span="span"  label="联系人" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入店铺联系人姓名" />
          </form-col>
          <form-col :span="span"  label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" />
          </form-col>
          <form-col label="营业时间" class="compact-time">
            <el-row :gutter="11">
              <el-col :span="9">
                <el-form-item prop="startTime">
                  <el-time-picker
                    v-model="form.startTime"
                    format="HH:mm"
                    value-format="HH:mm"
                    placeholder="开始时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="1" class="time-separator">—</el-col>
              <el-col :span="9">
                <el-form-item prop="endTime">
                  <el-time-picker
                    v-model="form.endTime"
                    format="HH:mm"
                    value-format="HH:mm"
                    placeholder="结束时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </form-col>
<!--          </form-col>-->
<!--          <form-col :span="span"  label="经度" prop="longitude">-->
<!--            <el-input v-model="form.longitude" placeholder="请输入经度" />-->
<!--          </form-col>-->
<!--          <form-col :span="span"  label="纬度" prop="latitude">-->
<!--            <el-input v-model="form.latitude" placeholder="请输入纬度" />-->
<!--          </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 :span="span"  label="门店照片" prop="picture">
            <image-upload v-model="form.picture" type="textarea" placeholder="请输入内容" />
          </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.latitude"
      :init-lng="form.longitude"
      @submit="onSubmitAddress"
      marker-type="store"
    />
  </div>

</template>

<script>
import { listStore, getStore, delStore, addStore, updateStore } from "@/api/bst/store";
import { $showColumns } from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import PlaceSearchDialog from "@/components/Map/PlaceSearch/PlaceSearchDialog.vue";
import StoreLink from "@/views/bst/store/StoreLink.vue";
import UserInput from "@/components/Business/User/UserInput.vue";

// 默认排序字段
const defaultSort = {
  prop: "createTime",
  order: "descending"
}

export default {
  name: "Store",
  mixins: [$showColumns],
  props: {
    query: {
      type: Object,
      default: () => ({})
    }
  },
  components: {UserInput, StoreLink, PlaceSearchDialog, FormCol},
  data() {
    return {
      span: 24,
      // 字段列表
      columns: [
        {key: 'storeId', visible: true, label: '店铺ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'storeName', visible: true, label: '店铺名称', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'address', visible: true, label: '详细地址', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'picture', visible: true, label: '门店照片', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'userName', visible: true, label: '商户', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'phone', visible: true, label: '联系电话', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'startTime', visible: true, label: '营业开始时间', minWidth: null, sortable: false, overflow: false, align: 'center', width: "100"},
        {key: 'endTime', visible: true, label: '营业结束时间', minWidth: null, sortable: false, overflow: false, align: 'center', width: "100"},
      ],
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 店铺表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        userId: null,
        storeName: null,
        userName: null,
        phone: null,
        startTime: null,
        endTime: null,
        longitude: null,
        latitude: null,
        address: null,
        picture: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "所属用户不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
         ],
          storeName: [
            { required: true, message: '店铺名不能为空', trigger: 'blur' }
          ],
          userName: [
            { required: true, message: '联系用户不能为空', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '联系方式不能为空', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '营业开始时间不能为空', trigger: 'change' },
          ],
          endTime: [
            { required: true, message: '营业结束时间不能为空', trigger: 'change' },
          ],
          address: [
          { required: true, message: '地址不能为空', trigger: 'blur' },
          ],
      },
      showPlaceSearchMap: false,
    };
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }
    this.getList();
  },
  methods: {
    // 查看按钮操作
    handleSee(row) {
      this.$router.push({path: `/view/store/${row.storeId}`})
    },
    onSubmitAddress(addr) {
      this.form.address = addr.name;
      this.form.latitude  = addr.lat;
      this.form.longitude  = addr.lng;
      this.form.province = addr.province;
      this.form.city = addr.city;
      this.form.county = addr.county;
      this.form.specificAddress = addr.name;
    },
    /** 当排序按钮被点击时触发 **/
    onSortChange(column) {
      if (column.order == null) {
        this.queryParams.orderByColumn = defaultSort.prop;
        this.queryParams.isAsc = defaultSort.order;
      } else {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
      }
      this.getList();
    },
    /** 查询店铺列表 */
    getList() {
      this.loading = true;
      listStore(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: null,
        storeName: null,
        userName: null,
        phone: null,
        startTime: null,
        province: "福建省",
        city: "宁德市",
        county: "福鼎市",
        endTime: null,
        longitude: null,
        latitude: null,
        address: null,
        picture: null,
        createTime: null
      };
      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 = "添加店铺";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const storeId = row.storeId || this.ids
      getStore(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) {
            updateStore(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStore(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const storeIds = row.storeId || this.ids;
      this.$modal.confirm('是否确认删除店铺编号为"' + storeIds + '"的数据项？').then(function() {
        return delStore(storeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bst/store/export', {
        ...this.queryParams
      }, `store_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
