<template>
  <div class="app-container">

    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="选品类型" prop="itemType">
        <el-select
          filterable
          v-model="queryParams.itemType"
          placeholder="请选择选品类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in queryParamsList.itemTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品ID：" prop="itemId">
        <el-input
          v-model="queryParams.itemId"
          placeholder="请输入商品id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="商品名称：" prop="itemTitle">
        <el-input
          v-model="queryParams.itemTitle"
          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"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="isLoading" :data="infoList">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column
        label="商品信息"
        align="center"
        prop="itemTitle"
        width="300"
        fixed="left"
      >
        <template slot-scope="scope">
          <div style="display: flex; width: 100%">
            <div style="width: 40%">
              <img
                :src="scope.row.imageUrl"
                alt=""
                style="width: 80px; height: auto"
              />
            </div>
            <div style="width: 60%" class="item-name-calss">
              <a
                style="
                      text-overflow: ellipsis;
                      white-space: nowrap;
                      overflow: hidden;
                      width: 100%;
                    "
                :title="scope.row.title"
              >
                {{ scope.row.title }}
              </a>
              <p align="left">Id： {{ scope.row.itemId }}</p>
              <p align="left">价格： {{ scope.row.skuPrice }}</p>

            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="类型"
        align="center"
        prop="activityItemStatus"
      >
        <template slot-scope="scope">
          <div v-if="!!scope.row.itemType">
            {{ scope.row.itemType | itemTypeName }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="绑定人" align="center" prop="userName"/>
      <el-table-column label="招商/采购" align="center" prop="courtshipPurchaseName"/>
      <el-table-column label="绑定日期" align="center" prop="dataCreateTime"/>
      <el-table-column label="一级类目" align="center" prop="parentCategoryName"/>
      <el-table-column label="所属类目" align="center" prop="categoryName"/>
      <el-table-column
        label="审核状态"
        align="center"
        prop="activityItemStatus"
      >
        <template slot-scope="scope">
          <div v-if="!!scope.row.auditStatus">
            {{ scope.row.auditStatus | auditStatusName }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px">
        <template slot-scope="scope">
          <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="600px" append-to-body :close-on-click-modal="false">

      <el-form ref="form" :model="form" :rules="rules" label-width="100px" :inline="true ">
        <el-form-item label="创建人：" prop="userName" style="width: 100%">
          {{ userName }}
        </el-form-item>

        <el-form-item label="选择小店：" prop="shopId" style="width: 100%">
          <el-select
            filterable
            v-model="form.shopId"
            placeholder="请选择商品所属小店"
            clearable
            style="width: 350px"
          >
            <el-option
              v-for="item in shopList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选品方式：" prop="itemType" class="entire-line" style="width: 100%">
          <el-radio-group v-model="form.itemType">
            <el-radio :label="1">自选品</el-radio>
            <el-radio :label="2">推品</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="招商/采购：" prop="courtshipPurchaseId" style="width: 100%">
          <el-select
            filterable
            v-model="form.courtshipPurchaseId"
            placeholder="请选择招商或采购"
            clearable
            style="width: 350px"
          >
            <el-option
              v-for="item in courtshipPurchaseIds"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="商品id：" prop="itemId">
          <el-input style="width: 350px" v-model="form.itemId" placeholder="请输入商品id"/>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="addLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {
  listInfo,
  getInfo,
  delInfo,
  addInfo,
  updateInfo,
  getShopList,
  getCourtshipPurchaseIds
} from "@/api/industry/item";


export default {
  name: "IndustryItemList",
  data() {
    return {
      shopList: [],
      courtshipPurchaseIds: [],
      userName: null,
      dateFile: null,
      fileList: [],
      uploadDate: new Date(),
      userId: null,
      addLoading: false,
      isLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemId: null,
        itemTitle: null,
        promoterId: null,
        promoterName: null,
        statDate: null,
        userId: null,
      },
      queryParamsList: {
        itemTypeList: [
          {value: 1, label: "自选品"},
          {value: 2, label: "推品"},
        ],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.userId = this.$store.getters.userId;
    this.userName = this.$store.getters.name;
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
    let date = new Date(start);
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? "0" + MM : MM;
    let dd = date.getDate();
    dd = dd < 10 ? "0" + dd : dd;
    this.uploadDate = `${y}-${MM}-${dd}`;

    this.getList();
  },

  filters: {
    itemTypeName(type) {
      const statusMap = {
        1: "自选品",
        2: "推品"
      };
      return statusMap[type];
    },

    auditStatusName(type) {
      const statusMap = {
        0: "待审核",
        1: "审核待修改",
        2: "审核通过",
        3: "审核拒绝",
      };
      return statusMap[type];
    },
  },

  methods: {
    getShopList() {
      getShopList({userId: this.userId}).then((res) => {
        this.shopList = res.data.map((item) => {
          return {
            label: item.shopId + '（' + item.shopName + '）',
            value: item.shopId,
          };
        });
      });
    },

    getCourtshipPurchaseIds() {
      getCourtshipPurchaseIds({userId: this.userId}).then((res) => {
        this.courtshipPurchaseIds = res.data.map((item) => {
          return {
            label: item.userId + '（' + item.userName + '）',
            value: item.userId,
          };
        });
      });
    },

    getList() {
      this.isLoading = true;
      this.queryParams.userId = this.userId;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.isLoading = false;
      });
    },


    getUploadDate() {
      let start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
      let date = new Date(start);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let dd = date.getDate();
      dd = dd < 10 ? "0" + dd : dd;
      this.uploadDate = `${y}-${MM}-${dd}`;
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
      this.userId = this.$store.getters.userId;
      this.userName = this.$store.getters.name;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "商品绑定";
      this.getShopList();
      this.getCourtshipPurchaseIds();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getShopList();
      this.getCourtshipPurchaseIds();
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data;
        this.userName = response.data.userName;
        this.open = true;
        this.title = "商品信息编辑";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.addLoading = true;
          if (this.form.id != null) {
            this.form.statDate = this.uploadDate;
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.addLoading = false;
              this.cancel();
              this.getList();
            }).catch((err) => {
              this.addLoading = false;
            })
          } else {
            this.form.userId = this.userId
            addInfo(this.form).then(response => {
              this.addLoading = false;
              this.$modal.msgSuccess("新增成功");
              this.cancel();
              this.getList();
            }).catch((err) => {
              this.addLoading = false;
            });
          }
        }
      });


    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除所选的数据项？').then(function () {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.getUploadDate();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

  }
};

</script>
