<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
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属区域" prop="parentName">
        <el-input
          v-model="queryParams.parentName"
          placeholder="请输入所属域名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区域名称" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter.native="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:part: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:part: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:part:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="partList" @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="partId" width="80"/>
      <el-table-column label="所属店铺" align="center">
        <template slot-scope="scope">
          <i class="el-icon-takeaway-box"/>
          <store-link
            :id="scope.row.storeId"
            :name="scope.row.storeName || '--'"
            size="mini"
          />
        </template>
      </el-table-column>
      <el-table-column label="区域名称" prop="partName" align="center" min-width="50">
        <template slot-scope="{row}">
            <span
              v-if="row.parentName"
            >
        {{ row.parentName }}/
      </span>
          {{ row.partName }}
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="picture">
        <image-preview slot-scope="d" :src="d.row.picture" :width="32" :height="32"/>
      </el-table-column>
      <el-table-column label="显示顺序" align="center" prop="orderNum" width="60"/>
      <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-edit"
            @click="handleUpdate(scope.row)"
            v-has-permi="['bst:part:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-has-permi="['bst:part: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="500px" 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="storeId">
            <el-select
              v-model="form.storeId"
              @change="handleStoreChange"
              placeholder="请选择店铺"
              clearable
              filterable
              :loading="loading"
            >
              <el-option
                v-for="item in storeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </form-col>
          <form-col :span="span" label="所属区域" prop="parentId" clearable>
            <el-cascader v-model="form.parentId"
                         :options="parentOptions"
                         :props="cascaderProps"
                         :disabled="!form.storeId"
                         placeholder="选定店铺后选择所属区域"
                         clearable
                         :show-all-levels="false"/>
          </form-col>
          <form-col :span="span" label="区域名称" prop="partName">
            <el-input v-model="form.partName" placeholder="请输入区域名称"/>
          </form-col>
          <form-col :span="span" label="区域图片" prop="picture">
            <image-upload v-model="form.picture"/>
          </form-col>
          <form-col :span="span" label="显示顺序" prop="orderNum">
            <el-input-number v-model="form.orderNum" controls-position="right" :min="1"></el-input-number>
          </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>
  </div>
</template>

<script>
import {listPart, getPart, delPart, addPart, updatePart} from "@/api/bst/part";
import {$showColumns} from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import {listStore} from "@/api/bst/store";
import DeptSelect from "@/components/Business/Dept/DeptSelect.vue";
import StoreLink from "@/views/bst/store/StoreLink.vue";

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

export default {
  name: "Part",
  mixins: [$showColumns],
  components: {StoreLink, DeptSelect, FormCol},
  data() {
    return {
      storeOptions: [], // 店铺域树数据
      parentOptions: [], // 父区域树数据
      cascaderProps: {
        value: 'partId',
        label: 'partName',
        children: 'children',
        checkStrictly: true,// 可单选任意级
        emitPath: false
      },
      span: 24,
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 区域列表表格数据
      partList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        storeId: null,
        parentId: null,
        partName: null,
        picture: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storeId: [
          {required: true, message: "所属店铺不能为空", trigger: "blur"}
        ],
        partName: [
          {required: true, message: "区域名称不能为空", trigger: "blur"}
        ],
        orderNum: [
          {required: true, message: "显示顺序不能为空", trigger: "blur"}
        ],
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getStoreList();
  },
  methods: {
    loadParentTree(storeId) {
      listPart({
        storeId: storeId,
      }).then(res => {
        this.parentOptions = this.handleTree(res.data, "partId", "parentId", "children");
        console.log(this.parentOptions)
      });
    },
    // 店铺选择变化处理
    handleStoreChange(storeId) {
      this.form.parentId = null;
      if (storeId) {
        this.loadParentTree(storeId);
      } else {
        this.parentOptions = [];
      }
    },
    /** 当排序按钮被点击时触发 **/
    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();
    },
    /** 查询店铺列表 */
    getStoreList() {
      this.loading = true;
      listStore().then(response => {
        this.storeOptions = (response.rows || []).map(item => ({
          value: item.storeId,
          label: item.storeName
        }))
        this.loading = false
      });
    },
    /** 查询区域列表列表 */
    getList() {
      this.loading = true;
      listPart(this.queryParams).then(response => {
        this.partList = response.data.rows || response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        partId: null,
        storeId: null,
        parentId: null,
        partName: null,
        picture: null,
        createTime: null,
        orderNum: 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.partId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.parentOptions = [];
      this.open = true;
      this.title = "添加区域列表";
      if (this.form.storeId) {
        this.loadParentTree(this.form.storeId);
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.parentOptions = [];
      const partId = row.partId || this.ids
      getPart(partId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改区域列表";
        if (this.form.storeId) {
          this.loadParentTree(this.form.storeId);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.partId != null) {
            updatePart(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPart(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const partIds = row.partId || this.ids;
      this.$modal.confirm('是否确认删除区域列表编号为"' + partIds + '"的数据项？').then(function () {
        return delPart(partIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bst/part/export', {
        ...this.queryParams
      }, `part_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

