<template>
  <div class="orderManage app-container">
    <div class="search">
      <div>
        <el-input
          v-model="query.billId"
          size="small"
          placeholder="请输入计费号"
          class="item-width-200"
        ></el-input>
        <el-input
          v-model="query.groupName"
          size="small"
          placeholder="请输入集团名称"
          class="item-width-200 ml10"
        ></el-input>
        <el-input
          v-model="query.planningName"
          size="small"
          placeholder="请输入产品策划名称"
          class="item-width-200 ml10"
        ></el-input>
        <el-input
          v-model="query.orderNo"
          size="small"
          placeholder="请输入订单号"
          class="item-width-200 ml10"
        ></el-input>
        <el-select
          v-model="query.groupType"
          size="small"
          clearable
          class="item-width-200 ml10"
          placeholder="请选择状态"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="query.actionID"
          size="small"
          clearable
          class="item-width-200 ml10"
          placeholder="请选择订单状态"
        >
          <el-option
            v-for="item in orderStatusoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-button
          class="ml10"
          type="primary"
          size="small"
          icon="el-icon-search"
          @click="handleSearch"
        >
          搜索
        </el-button>
      </div>
    </div>

    <el-table
      :data="tableData"
      tooltip-effect="dark"
      border
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column
        align="center"
        label="计费号"
        prop="billId"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="groupName"
        align="center"
        label="集团名称"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="orderNo"
        align="center"
        label="订单号"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="groupPlanName"
        align="center"
        label="订购产品策划名称"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="orderPrice"
        align="center"
        label="订购产品单价(元)"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column align="center" label="订购数量" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.orderNum || "--" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="orderDate"
        align="center"
        label="订购时间"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="invalidDate"
        align="center"
        label="失效时间"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        align="center"
        label="和校园推送时间"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ timeFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="groupType"
        align="center"
        label="状态"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-if="scope.row.groupType === 1">已生成</span>
          <span v-if="scope.row.groupType === 2">待生成</span>
          <span v-if="scope.row.groupType == 3">全部激活</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="未激活数量" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.totalTicket - scope.row.useTicket || "--" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="已激活数量" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.useTicket || "--" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="所属小程序" show-overflow-tooltip>
        <template slot-scope="scope">{{ "慧研学惠生活" }}</template>
      </el-table-column>
      <el-table-column
        prop="action"
        align="center"
        label="订单状态"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.action === 1" type="success">订购</el-tag>
          <el-tag type="danger" v-else-if="scope.row.action === 2">退订</el-tag>
          <el-tag type="info" v-else-if="scope.row.action === 3">激活</el-tag>
          <el-tag type="warning" v-else>暂停</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="address" align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            v-if="scope.row.groupType === 2"
            @click="gotoGenerating(scope.row)"
            >生成激活码</el-button
          >
          <el-button
            type="text"
            size="small"
            v-else
            @click="codeDetails(scope.row)"
            >查看激活码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="page-box">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="query.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="query.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="生成激活码"
      :visible.sync="vipDialogVisible"
      :before-close="closeVipDialog"
      width="50%"
    >
      <el-descriptions class="margin-top" :column="3" border>
        <el-descriptions-item>
          <template slot="label"> 计费号 </template>
          {{ codeData.billId || "--" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 集团名称 </template>
          {{ codeData.groupName || "--" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 订购时间 </template>
          {{ codeData.orderDate || "--" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 失效时间 </template>
          {{ codeData.invalidDate || "--" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 订购数量 </template>
          {{ codeData.orderNum || "--" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 所属平台 </template>
          慧研学惠生活
        </el-descriptions-item>
      </el-descriptions>
      <div class="codeInfo">激活码信息</div>
      <el-form
        :model="setQuery"
        ref="setQuery"
        :rules="rules"
        label-width="130px"
        size="small"
      >
        <el-form-item label="激活码有效期：" prop="validDay">
          <el-input
            v-model="setQuery.validDay"
            onkeyup="this.value=this.value.replace(/\D/g,'')"
            onafterpaste="this.value=this.value.replace(/\D/g,'')"
            class="item-width-100"
          ></el-input>
          天
        </el-form-item>
        <el-form-item label="会员套餐：" prop="selectType">
          <el-select
            v-model="setQuery.selectType"
            @change="selectChange"
            placeholder="请选择套餐"
          >
            <el-option
              v-for="(item, index) in optionsList"
              :key="item.value"
              :label="item.setMealName"
              :value="{ value: item.setMealCode, label: item.setMealName }"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员有效期：" prop="activationType">
          <el-radio-group v-model="setQuery.activationType">
            <el-radio
              v-for="item in radioOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-radio>
          </el-radio-group>
          <div v-if="setQuery.activationType == '时间段'">
            <el-form-item prop="startTime">
              <el-date-picker
                v-model="date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </div>
          <div v-if="setQuery.activationType == '天数'">
            <el-form-item prop="activationDay">
              <el-input
                v-model="setQuery.activationDay"
                onkeyup="this.value=this.value.replace(/\D/g,'')"
                onafterpaste="this.value=this.value.replace(/\D/g,'')"
                class="item-width-100"
              ></el-input>
              天
            </el-form-item>
          </div>
        </el-form-item>
        <div
          style="
            color: red;
            font-size: 12px;
            line-height: 16px;
            margin-left: 40px;
          "
        >
          注：会员有效期为用户使用激活码后会员生效时间。时间段为用户使用激活码后仅在对应时间段内拥有会员权益；天数为用户使用激活码后对应天数内拥有会员权益。时间段激活码无法叠加使用，天数激活码可叠加使用累计天数。
        </div>
        <el-form-item label="激活码数量：">
          <el-input
            v-model="setQuery.totalTicket"
            onkeyup="this.value=this.value.replace(/\D/g,'')"
            onafterpaste="this.value=this.value.replace(/\D/g,'')"
            class="item-width-100"
            @blur="totalTicketChange"
          ></el-input>
          <span style="color: red; font-size: 12px; margin-left: 10px"
            >注：默认为订购数量，激活码数量必须大于订购数量，输入数字须为整数</span
          >
        </el-form-item>
        <el-form-item label="激活码开头：" prop="startString">
          <el-input
            v-model="setQuery.startString"
            class="item-width-100"
          ></el-input>
          <span style="color: red; font-size: 12px; margin-left: 10px"
            >注：只能输入大小写英文和数字，创建激活码时放在激活码开头</span
          >
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="activationCancel('setQuery')">取 消</el-button>
        <el-button
          type="primary"
          :loading="updataLoading"
          @click="vipsubmitForm('setQuery')"
          >生成</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from "@/utils/index";
import { getGroupList, generateCode, getList } from "@/api/common";
import { timeFormat } from "@/utils/index";

export default {
  name: "orderManage",
  data() {
    return {
      date: "",
      updataLoading: false,
      codeData: {},
      optionsList: [],
      radioOptions: [
        {
          value: 1,
          label: "时间段",
        },
        {
          value: 2,
          label: "天数",
        },
      ],
      orderStatusoptions: [
        {
          value: 1,
          label: "订购",
        },
        {
          value: 2,
          label: "退订",
        },
        {
          value: 3,
          label: "激活",
        },
        {
          value: 4,
          label: "暂停",
        },
      ],
      statusOptions: [
        {
          value: 1,
          label: "已生成",
        },
        {
          value: 2,
          label: "待生成",
        },
        {
          value: 3,
          label: "全部激活",
        },
      ],
      setQuery: {
        validDay: "",
        activationType: "",
        activationDay: "",
        totalTicket: "",
        planningName: "",
        planningId: "",
        groupOrderNo: "",
        startString: "",
        startTime: "",
        endTime: "",
        selectType: "",
      },
      rules: {
        validDay: [
          {
            required: true,
            message: "请输入激活码有效期且必须为整数",
            trigger: "blur",
          },
        ],
        selectType: [
          { required: true, message: "请选择会员套餐", trigger: "change" },
        ],
        activationType: [
          {
            required: true,
            message: "请选择有效期(天数必须为整数)",
            trigger: "change",
          },
        ],
        endTime: [
          {
            required: true,
            message: "请至少选择一个有效期类型",
            trigger: "change",
          },
        ],
        activationDay: [
          {
            required: true,
            message: "请输入天数",
            trigger: "blur",
          },
        ],
        startTime: [
          {
            required: true,
            message: "请选择会员有效期",
            trigger: "change",
          },
        ],
        startString: [
          { required: true, message: "请输入激活码开头", trigger: "blur" },
        ],
      },
      vipDialogVisible: false,

      tableData: [],
      loading: false,
      query: {
        billId: "",
        groupName: "",
        orderNo: "",
        groupType: "",
        actionID: "",
        page: 1,
        size: 10,
      },
      title: "",
      total: 0,
    };
  },
  watch: {
    date(val) {
      if (val) {
        this.setQuery.startTime = new Date(val[0]).getTime();
        this.setQuery.endTime = new Date(val[1]).getTime();
      } else {
        this.setQuery.startTime = "";
        this.setQuery.endTime = "";
      }
    },
  },
  filters: {},
  methods: {
    // 重置表单
    activationCancel() {
      this.$refs["setQuery"].resetFields();
      this.vipDialogVisible = false;
    },
    closeVipDialog(done) {
      this.$refs["setQuery"].resetFields();
      done();
    },
    //  生成弹窗
    gotoGenerating(item) {
      this.get_setmealList();
      this.vipDialogVisible = true;
      this.codeData = item;
      this.setQuery.groupOrderNo = item.orderNo;
      this.setQuery.totalTicket = Math.floor(item.orderNum);
    },

    // 套餐选择
    selectChange(item) {
      const { value, label } = item;
      this.setQuery.planningId = value;
      this.setQuery.planningName = label;
    },

    // 判断激活套餐是否大于于订购数量
    totalTicketChange() {
      if (Math.trunc(this.codeData.orderNum) > this.setQuery.totalTicket) {
        this.$message.error("激活码数量必须大于订购数量");
        this.setQuery.totalTicket = "";
        return;
      }
    },

    // 提交生成逻辑处理
    vipsubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          delete this.setQuery.selectType;
          this.updataLoading = true;
          if (this.setQuery.activationType == "时间段") {
            this.setQuery.activationType = 1;
          } else {
            this.setQuery.activationType = 2;
          }
          this.submit_generateCode();
        } else {
          return false;
        }
      });
    },

    // 提交接口调用
    submit_generateCode() {
      generateCode(this.setQuery).then((res) => {
        this.updataLoading = false;
        if (res.state == "Success") {
          this.vipDialogVisible = false;
          this.getList();
          this.setQuery.validDay = "";
          this.setQuery.activationType = "";
          this.date = "";
          this.setQuery.totalTicket = "";
          setQuery.startString = "";
        }
      });
    },

    // 查看激活码
    codeDetails(item) {
      this.$router.push({
        path: "/operationManage/comboManage/checkoutCode",
        query: {
          groupInfo: JSON.stringify(item),
        },
      });
    },

    // 套餐列表
    get_setmealList() {
      this.loading = true;
      getList().then((res) => {
        this.loading = false;
        if (res.state == "Success") {
          this.optionsList = res.content.records;
        }
      });
    },

    handleSearch() {
      this.query.page = 1;
      this.getList();
    },
    timeFormat(val) {
      return timeFormat(val);
    },
    handleSizeChange(val) {
      this.query.page = 1;
      this.query.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.query.page = val;
      this.getList();
    },

    search() {
      this.query.page = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      let obj = JSON.parse(JSON.stringify(this.query));
      obj.page = obj.page - 1;
      // getOrderList
      getGroupList(obj).then((res) => {
        this.loading = false;
        if (res.state == "Success") {
          this.tableData = res.content.content;
          this.total = res.content.totalElements;
        }
      });
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style lang="scss">
.codeInfo {
  height: 50px;
  line-height: 50px;
  font-weight: 800;
  font-size: 16px;
  color: #000;
}
</style>
