<template>
  <div class="page">
    <topBar
      v-if="topList.length > 0"
      :topList="topList"
      :moren="moren"
    ></topBar>
    <div class="main">
      <div class="form_all">
        <el-form ref="select" :model="select" label-width="auto">
          <el-row :gutter="40">
            <!-- 一层 -->
            <el-col :span="4">
              <el-form-item :label="$t('产品编号')">
                <el-input clearable v-model="select.productCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :label="$t('产品名称')">
                <el-input clearable v-model="select.productName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :label="$t('是否上架')">
                <el-select v-model="select.isPutOn" clearable placeholder="">
                  <el-option label="是" :value="0"></el-option>
                  <el-option label="否" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button class="my_search" type="primary" @click="getDataList">
                {{ '搜索' }}</el-button
              >
              <el-button class="my_reset" @click="reset">
                {{ '重置' }}</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="main_a">
        <div class="mainbtn">
          <el-button
            v-hasButtons="['PickAdd']"
            size="small"
            @click="openDig"
            class="addBtn"
            >{{ '添加' }}</el-button
          >
          <el-button
            size="small"
            v-hasButtons="['PickExport']"
            style="background-color: #ff6723; color: #fff"
            @click="handleExport"
          >
            {{ '导出' }}</el-button
          >
        </div>
        <div class="maintable">
          <el-table
            :data="tableData"
            v-loading="loading"
            style="width: 100%"
            height="710px"
            :header-cell-style="{ background: '#EEEEEE' }"
            :row-class-name="tableRowClassName"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
              align="center"
              prop="productCode"
              width="150"
              :label="$t('产品编号')"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="productName"
              width="300"
              :label="$t('产品名称')"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="specsName"
              width="150"
              show-overflow-tooltip
              :label="$t('产品规格')"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="isPutOn"
              :label="$t('是否上架')"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.isPutOn == 1">{{ $t("否") }}</span>
                <span v-else>{{ $t("是") }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="showPrice"
              :label="$t('显示价格')"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="creationTime"
              :label="$t('创建时间')"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="time"
              :label="'操作'"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button
                  class="colors"
                  type="text"
                  size="small"
                  v-hasButtons="['PickEdit']"
                  @click.native.prevent="updateShow(scope.row)"
                >
                  {{ '修改' }}
                </el-button>
                <el-button
                  v-if="scope.row.isPutOn == 1"
                  @click="toFixed(scope.row.pkId, 0)"
                  type="text"
                  style="color: #48b2fd"
                  v-hasButtons="['PickStatus']"
                  size="small"
                >
                  {{ $t("上架") }}
                </el-button>
                <el-button
                  v-if="scope.row.isPutOn == 0"
                  @click="toFixed(scope.row.pkId, 1)"
                  type="text"
                  v-hasButtons="['PickStatus']"
                  style="color: #f3a900"
                  size="small"
                >
                  {{ $t("下架") }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getDataList"
    />
    <el-dialog
      :title="title"
      :visible.sync="dialogVisibleProduct"
      :close-on-click-modal="false"
      width="50%"
      center
      :before-close="handleCloseProduct"
    >
      <el-form
        ref="formsProduct"
        :model="selectedProduct"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="selectedProduct.productName"
            readonly
            @focus="getProduct()"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品规格" prop="specsName">
          <el-input disabled v-model="selectedProduct.specsName"></el-input>
        </el-form-item>
        <el-form-item label="显示价格" prop="showPrice">
          <el-input v-model="selectedProduct.showPrice"></el-input>
        </el-form-item>
        <el-form-item label="可提数量" prop="availableQuantity">
          <el-input-number
            v-model="selectedProduct.availableQuantity"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否上架">
          <el-switch :disabled="isPutOns" v-model="selectedProduct.isPutOn" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseProduct">{{ $t("取消") }}</el-button>
        <el-button type="primary" @click="saveProduct">{{
          $t("确定")
        }}</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="'添加'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      center
      :before-close="handleClose"
    >
      <div class="cpHeight">
        <el-row>
          <el-col :span="22">
            <el-input
              v-model="select.queryInfo"
              clearable
              :placeholder="'请输入'"
              @keyup.enter.native="getDataLists"
              prefix-icon="el-icon-search"
            ></el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" size="small" @click="getDataLists">
              {{ '搜索' }}</el-button
            >
          </el-col>
        </el-row>
        <div style="height: 10px" />
        <el-table
          ref="multipleTable"
          :data="dialogList"
          style="width: 100%"
          :header-cell-style="{ background: '#EEEEEE' }"
          :row-class-name="tableRowClassName"
          @select-all="onSelectAll"
          @select="selected"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            align="center"
            prop="productName"
            :label="'产品名称'"
          />
          <el-table-column
            align="center"
            prop="productCode"
            :label="'产品编号'"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="productName"
            :label="'规格'"
          >
            <template slot-scope="scope">
              <div
                v-show="
                  scope.row.selSkuNameList == '' ||
                  scope.row.selSkuNameList == undefined
                "
                class="blueCor"
                @click="selSku(scope.row.pkId, scope.$index)"
              >
                {{ '选择规格' }}
              </div>
              <div
                v-show="
                  scope.row.selSkuNameList != '' &&
                  scope.row.selSkuNameList != undefined
                "
                class="blueCor"
                @click="selSku(scope.row.pkId, scope.$index)"
              >
                {{ scope.row.selSkuNameList }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page-sizes="[10, 20, 30, 40]"
        :page.sync="queryParamsProcut.pageNum"
        :limit.sync="queryParamsProcut.pageSize"
        @pagination="getDataLists"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">{{ '取消' }}</el-button>
        <el-button type="primary" @click="sureProduct">{{
          '确认'
        }}</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="'规格'"
      :visible.sync="ggVisible"
      :close-on-click-modal="false"
      width="40%"
      center
      :before-close="handleCloseGg"
    >
      <div>
        <el-form>
          <el-form-item
            v-for="(item, index) in skuList"
            :key="index"
            :label="item.typeName"
          >
            <el-radio-group v-model="item.pkProductSku">
              <el-radio
                v-for="(ctem, cndex) in item.specsList"
                :key="ctem.pkId"
                :label="ctem.pkId"
                @change="getCheckBox(item.pkId, item.specsName)"
                >{{ ctem.specsName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseGg">{{ '取消' }}</el-button>
        <el-button type="primary" @click="sureSku">{{
          '确认'
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import topBar from "@/components/topBar";
import * as api from "@/api/giftGoods.js";
export default {
  name: "Bzpz",
  components: {
    topBar,
  },
  filters: {
    isAgree(val) {
      if (!val) {
        return '允许';
      } else {
        return '禁止';
      }
    },
  },
  data() {
    return {
      isPutOns: false,
      dialogList: [], // 产品数组
      creationTime: [],
      creationTime1: [],
      creationTime2: [],
      select: {},
      selectedProduct: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
      },
      queryParamsProcut: {
        pageNum: 1,
        pageSize: 10,
      },
      addOrEdit: "",
      total: 0,
      dialogVisible: false,
      ggVisible: false,
      tableData: [],
      loading: false,
      moren: "PickList",
      topList: [
        {
          name: "提货商品维护",
          path: "PickList",
        },
      ],
      form: {
        name: "",
      },
      actStatus: [],
      selectData: [], // 选中
      skuList: [], // 规格数组
      selSkuList: "",
      selSkuNameList: "",
      selIndex: "",
      showCndex: "",
      showIndex: "",
      dialogVisibleProduct: false,
      types: 1,
      title: "",
      rules: {
        productName: [
          {
            required: true,
            message: this.$t("请选择产品"),
            trigger: "blur",
          },
        ],
        specsName: [
          {
            required: true,
            message: this.$t("请选择产品规格"),
            trigger: "blur",
          },
        ],
        showPrice: [
          { required: true, message: this.$t("请填写价格"), trigger: "blur" },
        ],
        availableQuantity: [
          { required: true, message: this.$t("请填写数量"), trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getDataLists();
    // 获取列表
    this.getDataList();
  },
  methods: {
    toFixed(id, status) {
      const msg = status ? "是否下架" : "是否上架";
      this.$confirm(msg, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
      }).then(() => {
        api
          .pickProductStatus({
            pkId: id,
            isPutOn: status,
          })
          .then((res) => {
            if (res.code === 200) {
              this.$message({
                message: res.msg,
                type: "success",
              });
              this.getDataList();
            }
          });
      });
    },
    saveProduct() {
      this.selectedProduct.isPutOn = this.selectData.isPutOn ? 0 : 1;
      this.$refs["formsProduct"].validate((valid) => {
        if (!valid) {
          if (!this.selectedProduct.specsName) {
            this.$message({
              message: this.$t("请选择产品规格"),
              type: "warning",
            });
          }
          return false;
        } else {
          if (this.types == 1) {
            api.pickProductSave(this.selectedProduct).then((res) => {
              if (res.code == 200) {
                this.$message({
                  message: res.msg,
                  type: "success",
                });
                this.dialogVisibleProduct = false;
                this.$refs["formsProduct"].clearValidate();
                this.$refs["formsProduct"].resetFields();
                this.getDataList();
              }
            });
          } else if (this.types == 2) {
            api.pickProductUpdate(this.selectedProduct).then((res) => {
              if (res.code == 200) {
                this.$message({
                  message: res.msg,
                  type: "success",
                });
                this.dialogVisibleProduct = false;
                this.$refs["formsProduct"].clearValidate();
                this.$refs["formsProduct"].resetFields();
                this.getDataList();
              }
            });
          }
        }
      });
    },
    openDig() {
      this.types = 1;
      this.title = this.$t("新增提货商品");
      this.selectedProduct.availableQuantity = 0;
      this.dialogVisibleProduct = true;
    },
    updateShow(item) {
      this.types = 2;
      this.title = this.$t("修改提货商品");
      api.getOnePickProduct(item.pkId).then((res) => {
        if (res.code === 200) {
          this.dialogVisibleProduct = true;
          this.selectedProduct = res.data;
          this.selectedProduct.isPutOn = res.data.isPutOn ? false : true;
          this.selectedProduct.productName = item.productName;
        }
      });
    },
    handleCloseProduct() {
      this.selectedProduct = {};
      this.isPutOns = false;
      this.dialogVisibleProduct = false;
    },
    getProduct() {
      this.getDataLists();
      this.dialogVisible = true;
    },
    handleClose() {
      this.selectData = [];
      this.select = {};
      this.dialogVisible = false;
    },
    handleCloseGg() {
      this.ggVisible = false;
    },
    getDataLists() {
      if (this.types == 2) {
        this.select.queryInfo = this.selectedProduct.productName;
      }
      api
        .getProductAll(
          Object.assign({ isPutOn: 0 }, this.queryParamsProcut, this.select, {
            isExistSpecs: 1,
          })
        )
        .then((res) => {
          res.rows.forEach((item) => {
            item.quantity = 1;
          });
          this.dialogList = res.rows;
          this.total = res.total;
        });
    },
    onSelectAll() {
      this.$refs.multipleTable.clearSelection();
    },
    selected(selection, row) {
      // 清除 所有勾选项
      this.$refs.multipleTable.clearSelection();
      // 当表格数据都没有被勾选的时候 就返回
      // 主要用于将当前勾选的表格状态清除
      if (selection.length == 0) return;
      this.$refs.multipleTable.toggleRowSelection(row, true);
      this.selectData = row;
    },
    getCheckBox() {
      const arr1 = [];
      const arr2 = [];
      this.skuList.forEach((item) => {
        item.specsList.forEach((ctem) => {
          if (ctem.pkId == item.pkProductSku) {
            arr1.push(ctem.pkId);
            arr2.push(ctem.specsName);
          }
        });
      });
      this.selSkuList = arr1.join(",");
      this.selSkuNameList = arr2.join(",");
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return "warning-row";
      } else if (rowIndex % 2 == 0) {
        return "success-row";
      }
      return "";
    },
    selSku(pkId, index) {
      this.selIndex = index;
      api
        .getProductSpecs({
          pkProduct: pkId,
        })
        .then((res) => {
          const arr1 = [];
          const arr2 = [];
          res.data.forEach((item) => {
            item.pkProductSku = item.specsList[0].pkId;
            arr1.push(item.specsList[0].pkId);
            arr2.push(item.specsList[0].specsName);
          });
          this.selSkuList = arr1.join(",");
          this.selSkuNameList = arr2.join(",");

          this.skuList = res.data;
          this.ggVisible = true;
        });
    },
    sureSku() {
      this.$set(this.dialogList[this.selIndex], "selSkuList", this.selSkuList);
      this.$set(
        this.dialogList[this.selIndex],
        "selSkuNameList",
        this.selSkuNameList
      );
      this.ggVisible = false;
    },
    sureProduct() {
      console.log(this.selectData, "selectData");
      if (this.selectData.length == 0) {
        this.$message({
          message: '请选择产品',
          type: "warning",
        });
        return false;
      } else {
        this.selectedProduct.pkProduct = this.selectData.pkId;

        this.selectedProduct.productName = this.selectData.productName;

        this.selectedProduct.availableQuantity = this.selectData.quantity;

        this.selectedProduct.specsName = this.selectData.selSkuNameList;

        this.selectedProduct.specsNameId = parseInt(this.selectData.selSkuList);
        this.selectedProduct.isPutOn = true;
        this.isPutOns = true;
        this.handleClose();
        this.$forceUpdate();
      }
    },
    //重置
    reset() {
      this.select = {};
      this.creationTime = [];
      this.creationTime1 = [];
      this.creationTime2 = [];
      this.getDataList();
    },
    getData() {
      api.activityStatus().then((res) => {
        this.actStatus = res.data;
      });
    },
    changeTime(val) {
      this.select.actStartDate = val ? val[0] : "";
      this.select.actEndDate = val ? val[1] : "";
    },
    // 获取列表
    getDataList() {
      this.loading = true;
      api
        .pickProductList(Object.assign({}, this.queryParams, this.select))
        .then((res) => {
          this.tableData = res.rows;
          this.total = res.total;
          this.loading = false;
        });
    },
    handleSelectionChange(val) {},
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
      }).then((_) => {
        this.download(
          "activity/manage/pick-product/export",
          Object.assign({}, this.queryParams, this.select),
          `提货商品${new Date().getTime()}.xlsx`
        );
      });
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-table .warning-row {
  background: #f9f9f9;
}
.blueCor {
  color: #589ff8;
  cursor: pointer;
}
::v-deep .el-table .success-row {
  background: #ffffff;
}
::v-deep .el-table thead {
  color: #000000;
}
::v-deep .el-select {
  width: 100%;
}
.page {
  padding: 20px;
  background: #f9f9f9;
  font-size: 14px;
  .main {
    // background: #ffffff;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    .main_a {
      background: #fff;
      border-radius: 8px;
      justify-content: space-between;
      align-items: center;
      box-shadow: 0px 2px 20px 0px rgba(238, 238, 238, 0.5);
    }
    .mainbtn {
      padding: 0;
    }
    .maintable {
      flex: 1;
    }
  }
}
::v-deep .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
.form_all {
  padding: 0 20px;
  margin-bottom: 10px;
  background: #fff;
}
</style>
