<template>
  <div id="commodityManageMent">
    <search-box-new
      ref="searchBox"
      :formData="formData"
      :formList="formList"
      @search="search"
      @init="init"
      :topType="topType"
    />
    <table-list
      ref="tableList"
      :tableSets="tableSet"
      :tableData="tableData"
      :navText="navText"
      @addClick="addClick"
      :loading="loading"
      @editInfo="editInfo"
      @openClassNum="openClassNum"
      rowKey="goodsId"
    >
      <template slot="customize">
        <el-button
          size="medium"
          v-if="isShowCopy"
          @click="handelCopy"
          type="success"
          >商品复制</el-button
        >
        <el-button size="medium" @click="handelBatch(1)" type="success"
          >批量上架</el-button
        >
        <el-button size="medium" @click="handelBatch(0)" type="success"
          >批量下架</el-button
        >
        <el-button size="medium" @click="handelBatch(2)" type="warning"
          >批量删除</el-button
        >
      </template>
      <template slot="btn" slot-scope="props">
        <el-button
          v-if="
            props.scope.row.goodsType == 1 &&
            props.scope.row.courseNum &&
            props.scope.row.courseNum > 0 &&
            props.scope.row.goodsLearningOrder == 0
          "
          type="text"
          @click="setTeacher(props.scope.row)"
          >双师制设置</el-button
        ><el-button
          v-if="props.scope.row.examRecord"
          type="text"
          @click="$refs.dayPracticeSet.open(props.scope.row.goodsId)"
          >每日一练设置</el-button
        >
        <el-button type="text" @click="addClick(props.scope.row, 0)"
          >修改</el-button
        >
        <el-button type="text" @click="changeStatus(props.scope.row)">{{
          props.scope.row.goodsStatus === 1 ? "下架" : "上架"
        }}</el-button>
        <el-button
          type="text"
          v-if="props.scope.row.specTemplateId"
          @click="cancelBind(props.scope.row.goodsId, 0)"
          >取消绑定</el-button
        >
        <el-button type="text" @click="del(props.scope.row)">删除</el-button>
      </template>
    </table-list>
    <pagination
      :total="total"
      :pageSize="formData.pageSize"
      :currentPage="formData.pageNum"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <el-dialog
      :visible.sync="dialogVisible"
      width="1000px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">关联商品规格</div>
        <div class="rightBoxs">
          <img
            src="@/assets/images/Close@2x.png"
            alt=""
            @click="dialogVisible = false"
          />
        </div>
      </div>
      <div style="margin-bottom: 10px">
        <!-- 搜索框 -->
        <el-input
          style="width: 230px; margin: 0px 10px"
          size="small"
          v-model="specFormData.templateName"
          placeholder="商品规格模板名称"
        ></el-input>
        <el-button
          size="small"
          type="primary"
          @click="searchGoodsSpecList(specFormData.goodsId)"
          >查询</el-button
        >
      </div>
      <table-list
        :tableSets="dialogTableSet"
        :tableData="dialogTableData"
        :navText="dialogNavText"
        :radio.sync="tableRadio"
      >
      </table-list>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <Day-practice-set-dialog ref="dayPracticeSet"></Day-practice-set-dialog>
    <Base-dialog
      title="商品复制机构选择"
      :isShow.sync="dialogCopyVisible"
      @submit="goodsCopy"
      :disabledBtn="copyLoading"
    >
      <el-radio-group v-model="tenantId">
        <el-radio
          style="display: block; margin-bottom: 10px"
          :label="item.tenantId"
          v-for="item in tenantList"
          :key="item.tenantId"
          >{{ item.tenantName }}</el-radio
        >
      </el-radio-group>
    </Base-dialog>
  </div>
</template>

<script>
import searchBoxNew from "@/components/searchBoxNew";
import tableList from "@/components/tableList";
import pagination from "@/components/pagination";
import DayPracticeSetDialog from "./DayPracticeSetDialog.vue";
import {
  getGoodsSpecList,
  goodsUpdateSpec,
  goodsUpdateStatus,
  goodsDel,
  goodCancelBind,
  getTenantList,
  goodsCopy,
} from "@/api/resource/good";
export default {
  name: "CommodityManageMent",
  components: { searchBoxNew, tableList, pagination, DayPracticeSetDialog },
  data() {
    return {
      loading: false, //当前表单加载是否加载动画
      copyLoading: false,
      navText: {
        title: "商品列表",
        index: 0,
        ch: "条",
        num: false,
        border: true,
        choice: true,
        addHide: false,
        changeWidth: "180px",
        openCheckMore: true,
        backFatherBtn: {
          status: false,
          title: "未定义",
        },
      },
      topType: true,
      //搜索
      formList: [
        {
          prop: "educationTypeId",
          placeholder: "教育类型",
          scope: "educationType",
        },
        {
          prop: "businessId",
          placeholder: "业务层次",
          scope: "businessLevel",
          edu: "educationTypeId",
        },
        {
          prop: "schoolId",
          placeholder: "院校",
          scope: "schoolList",
          edu: "educationTypeId",
        },
        {
          prop: "majorId",
          placeholder: "专业",
          scope: "Professional",
          edu: "educationTypeId",
        },
        {
          prop: "subjectId",
          placeholder: "科目",
          scope: "sujectType",
          edu: "educationTypeId",
        },
        {
          prop: "status",
          placeholder: "商品状态",
          scope: "select",
          noClear: false,
          options: [
            {
              label: "全部状态",
              value: "0,1",
            },
            {
              label: "有效",
              value: 1,
            },
            {
              label: "无效",
              value: 0,
            },
          ],
        },
        {
          prop: "goodsStatus",
          placeholder: "前台可售状态",
          scope: "select",
          options: [
            {
              label: "已上架",
              value: 1,
            },
            {
              label: "未上架",
              value: 0,
            },
          ],
        },
        {
          prop1: "validityStartTime",
          prop2: "validityEndTime",
          placeholder1: "商品有效期开始时间",
          placeholder2: "商品有效期结束时间",
          scope: "moreDataPicker",
        },
        // {
        //   prop: "orderGoodsStatus",
        //   placeholder: "退款状态",
        //   scope: "select",
        //   options: [
        //     {
        //       label: "已退款",
        //       value: 1,
        //     },
        //     {
        //       label: "退款中",
        //       value: 2,
        //     },
        //     {
        //       label: "拒绝退款",
        //       value: 3,
        //     },
        //   ],
        // },
        {
          prop: "goodsName",
          placeholder: "请输入商品名称",
        },
      ],
      formData: {
        goodsType: "",
        status: "0,1",
        pageSize: 10,
        pageNum: 1,
      },
      // 表单
      tableSet: [
        {
          label: "商品名称",
          prop: "goodsName",
          scope: "editInfo",
          hidden: true,
        },
        {
          label: "商品编码",
          prop: "code",
          hidden: false,
        },
        {
          label: "专业",
          prop: "categoryName",
          hidden: true,
        },
        {
          label: "院校",
          prop: "schoolName",
          hidden: false,
        },
        {
          label: "科目",
          prop: "subjectNames",
          hidden: true,
        },
        {
          label: "关联商品规格",
          prop: "specTemplateId",
          hidden: true,
          scope: "aboutSpec",
        },
        {
          label: "业务层次",
          prop1: "projectName",
          prop2: "businessName",
          hidden: false,
          scope: "InfoMore",
        },
        {
          label: "教育类型",
          prop: "educationName",
          hidden: false,
        },
        {
          label: "学时",
          prop: "classHours",
          hidden: true,
        },
        {
          label: "商品内容视图",
          hidden: true,
          scope: "treeWatch",
        },
        {
          label: "商品价格",
          prop: "standPrice",
          hidden: true,
          scope: "leftCh",
          ch: "￥",
        },
        {
          label: "商品划线价",
          prop: "linePrice",
          hidden: true,
          scope: "leftCh",
          ch: "￥",
        },
        {
          label: "商品状态",
          prop: "status",
          hidden: false,
          scope: "hasTime",
        },
        {
          label: "商品有效期",
          prop1: "validityStartTime",
          prop2: "validityEndTime",
          scope: "TimeLists",
          Diszing: false,
          hidden: true,
        },
        {
          label: "学习服务期",
          prop1: "serviceTimeType",
          prop2: "serviceTimeNum",
          prop3: "studyStartTime",
          prop4: "studyEndTime",
          scope: "studentServicePeriod",
          hidden: true,
        },
        {
          label: "供应方（服务）",
          prop: "supplyName",
          hidden: false,
        },
        {
          label: "最后编辑时间",
          prop: "updateTime",
          hidden: true,
          scope: "aTimeList",
        },
        {
          label: "创建时间",
          prop: "createTime",
          hidden: true,
          scope: "aTimeList",
        },
        {
          label: "可售状态",
          prop: "goodsStatus",
          hidden: true,
          scope: "status",
        },
        {
          label: "同步时间",
          prop: "copyTime",
          hidden: sessionStorage.TenantId == 867735392558919680,
          scope: "copyTime",
        },
      ],
      tableData: [], //表单数据
      total: 0, //一共多少条
      dialogVisible: false,
      dialogCopyVisible: false,
      dialogTableSet: [
        {
          label: "教育类型",
          prop: "educationName",
          hidden: true,
        },
        {
          label: "业务层次",
          prop: "businessName",
          hidden: true,
        },
        {
          label: "商品规格模板名称",
          prop: "name",
          hidden: true,
        },
        {
          label: "商品规格数量",
          prop: "specNumber",
          hidden: true,
        },
      ],
      dialogTableData: [],
      dialogNavText: {
        index: 0,
        num: false,
        border: true,
        choice: false,
        choiceRadio: true,
        radioKey: "specTemplateId",
        radioFixed: false,
        addHide: !false,
        tableHide: true,
        dontNum: true,
        headShow: false,
        backFatherBtn: {
          status: false,
          title: "未定义",
        },
      },
      tableRadio: "",
      specFormData: {
        templateName: "",
        goodsId: "",
      },
      tenantList: [],
      tenantId: "",
    };
  },
  mounted() {
    this.search();
  },
  activated() {
    this.search();
  },
  methods: {
    // 取消规格绑定
    cancelBind(goodsId) {
      this.$confirm(`此操作将该商品取消关联规格模板, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          goodCancelBind({
            goodsId,
          }).then((res) => {
            this.$message.success("取消关联成功");
            this.search(1);
          });
        })
        .catch(() => {});
    },
    handelCopy() {
      this.dialogCopyVisible = true;
      getTenantList().then((res) => {
        this.tenantList = res.data;
      });
    },
    goodsCopy() {
      if (!this.tenantId) {
        return this.$message.warning("请选择机构");
      }
      let data = this.$refs.tableList.allCheckData;
      if (!data.length) {
        return this.$message.warning("请先勾选商品");
      }
      this.copyLoading = true;
      const goodsIds = data.map((item) => item.goodsId);
      goodsCopy({ goodsIds, tenantId: this.tenantId })
        .then((res) => {
          this.dialogCopyVisible = false;
          this.$refs.tableList.clearMoreActive();
          this.$message.success("商品复制成功");
        })
        .finally((e) => {
          this.copyLoading = false;
        });
    },
    // 批量上下架
    handelBatch(type) {
      let len = this.$refs.tableList.allCheckData.length;
      if (!len) {
        return this.$message.warning("请先勾选商品");
      }
      let name = ["下架", "上架", "删除"][type];
      this.$confirm(`此操作将所勾选的${len}条商品${name}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const goodsIds = this.$refs.tableList.allCheckData.map(
            (item) => item.goodsId
          );
          if (type == 2) {
            goodsDel({
              status: -1,
              ids: goodsIds,
            }).then((res) => {
              this.$message.success("批量删除成功");
              this.$refs.tableList.clearMoreActive();
              this.search(1);
            });
          } else {
            goodsUpdateStatus({
              goodsStatus: type,
              goodsIds,
            }).then((res) => {
              this.$message.success(`批量${name}成功`);
              this.$refs.tableList.clearMoreActive();
              this.search(1);
            });
          }
        })
        .catch(() => {});
    },
    openClassNum(id) {
      this.specFormData.goodsId = id;
      this.tableRadio = "";
      let { specTemplateId } = this.tableData.find((e) => e.goodsId == id);
      this.tableRadio = specTemplateId || "";
      this.searchGoodsSpecList(id);
      this.dialogVisible = true;
    },
    searchGoodsSpecList(id) {
      // this.specFormData
      getGoodsSpecList(id).then((res) => {
        this.dialogTableData = res.data;
      });
    },
    editInfo(v) {
      this.addClick(v, 0);
    },
    search(int) {
      this.loading = true;
      if (int === 1) {
        this.formData.pageNum = 1;
      }
      if (int === 2) {
        this.formData = {
          goodsType: "",
          status: "0,1",
          pageSize: 10,
          pageNum: 1,
        };
      }
      if (int === 3) {
        this.formData.pageNum = 1;
      }
      var data = JSON.parse(JSON.stringify(this.formData));
      if (this.formData.validityStartTime) {
        data.validityStartTime = data.validityStartTime / 1000;
      }
      if (this.formData.validityEndTime) {
        data.validityEndTime = data.validityEndTime / 1000;
      }
      this.$api
        .inquireGoods(data)
        .then((res) => {
          this.tableData = res.rows;
          this.total = res.total;
          this.navText.index = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    init() {
      this.search(2);
    },
    del(v) {
      this.$api.gradecheckGoodsChange({ goodsId: v.goodsId }).then((res) => {
        if (res.data > 0) {
          this.$message.error("已有学员正在学习该商品，无法删除");
          return;
        } else {
          this.$alert(
            "确定删除此内容？<br />内容删除后将无法恢复，请慎重考虑",
            "提示",
            {
              dangerouslyUseHTMLString: true,
            }
          )
            .then(() => {
              var data = {
                goodsId: v.goodsId,
                status: -1,
              };
              this.$api.editGoods(data).then((res) => {
                this.$message.success("删除成功");
                this.search();
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
        }
      });
    },
    //双师制设置
    setTeacher(data) {
      const jump = () => {
        this.$router.push({
          path: "commoditySetTeacher",
          query: {
            id: data.goodsId,
          },
        });
      };
      const statusPage = this.$store.state.tagsView.visitedViews.some(
        (item) => {
          return item.name == "CommoditySetTeacher";
        }
      );
      if (statusPage) {
        this.$store
          .dispatch("tagsView/delCachedView", {
            name: "CommoditySetTeacher",
          })
          .then((res) => {
            jump();
          });
      } else {
        jump();
      }
    },
    addClick(v, int) {
      if (v === undefined) {
        this.$router.push({
          path: "commodityManageMentAdd",
        });
      } else {
        const jump = () => {
          this.$router.push({
            path: "commodityManageMentEdit",
            query: {
              id: v.goodsId,
            },
          });
        };
        const statusPage = this.$store.state.tagsView.visitedViews.some(
          (item) => {
            return item.name == "CommodityManageMentEdit";
          }
        );
        if (statusPage) {
          this.$store
            .dispatch("tagsView/delCachedView", {
              name: "CommodityManageMentEdit",
            })
            .then((res) => {
              jump();
            });
        } else {
          jump();
        }
      }
    },
    handleSizeChange(v) {
      this.formData.pageSize = v;
      this.formData.pageNum = 1;
      this.search();
    },
    handleCurrentChange(v) {
      this.formData.pageNum = v;
      this.search();
    },
    changeStatus(item) {
      var items = JSON.parse(JSON.stringify(item));
      items.goodsStatus = items.goodsStatus === 1 ? 0 : 1;
      this.$api.editGoods(items).then((res) => {
        if (item.goodsStatus === 1) {
          this.$message.success("下架成功");
        } else {
          this.$message.success("上架成功");
        }
        this.search();
      });
    },
    submit() {
      if (!this.tableRadio) {
        return this.$message({
          message: "请选择关联商品规格",
          type: "warning",
        });
      }
      goodsUpdateSpec({
        goodsId: this.specFormData.goodsId,
        specTemplateId: this.tableRadio,
      }).then((res) => {
        this.dialogVisible = false;
        this.search();
      });
    },
  },
  computed: {
    isShowCopy() {
      return sessionStorage.TenantId == "867735392558919680";
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-button {
  border-radius: 8px;
}

/deep/.el-dialog {
  border-radius: 8px;

  .el-dialog__header {
    padding: 0;

    .hearders {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 18px 0px 20px;
      border-bottom: 1px solid #e2e2e2;

      .leftTitle {
        font-size: 14px;
        font-weight: bold;
        color: #2f4378;
      }

      .rightBoxs {
        display: flex;
        align-items: center;

        img {
          width: 14px;
          height: 14px;
          margin-left: 13px;
          cursor: pointer;
        }
      }
    }
  }

  .el-dialog__footer {
    padding: 0;

    .dialog-footer {
      padding: 0px 40px;
      height: 70px;
      border-top: 1px solid #e2e2e2;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}

.imgBox {
  width: 100%;
  // height: 210px;
  border: 1px solid #e2e2e2;
  border-radius: 8px;
  padding: 8px 8px 3px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .imgLabel {
    flex: 1;
    width: 100%;
    border: 1px dotted #e2e2e2;
    color: #999;
    font-size: 14px;
    cursor: pointer;
    border-radius: 8px;

    .msPhoto {
      display: flex;
      justify-content: center;
      align-items: center;
      max-width: 100%;
      max-height: 270px;

      img {
        max-width: 100%;
        max-height: 270px;
      }
    }

    .imgbbx {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;

      i {
        font-weight: bold;
        margin: 14px 0;
        font-size: 24px;
      }
    }
  }

  p {
    margin: 5px 0px;
  }
}
</style>

