<template>
  <template-page
    v-if="pageShow"
    ref="pageRef"
    :get-list="getList"
    :exportList="exportList"
    :table-attributes="tableAttributes"
    :table-events="tableEvents"
    :options-evens-group="optionsEvensGroup"
    :moreParameters="moreParameters"
    :column-parsing="columnParsing"
    :operation="operation()"
    key="pageType"
  >
    <div class="cartographer_big">
      <el-dialog
        title="优惠券"
        width="100%"
        :modal="false"
        :visible.sync="formDialog"
        :before-close="handleClose"
      >
        <zj-page-container>
          <zj-page-fill>
            <div style="box-sizing: border-box; padding: 20px 20px 0 20px">
              <zj-form-container
                ref="formRef"
                :form-data="formData"
                :form-attributes="{ size: 'mini' }"
              >
                <zj-form-module
                  title="基本信息"
                  label-width="120px"
                  :form-data="formData"
                  :form-items="formItems"
                >
                </zj-form-module>
                <zj-form-module
                  v-if="formData.receiveCrowd === 2 && xiangqing"
                  title="指定用户"
                  label-width="120px"
                  :form-data="formData"
                  :form-items="ysfFormItems"
                >
                </zj-form-module>
                <zj-form-module
                  v-if="formData.receiveCrowd === 2 && !xiangqing"
                  title="指定用户"
                  label-width="120px"
                  :form-data="formData"
                  :form-items="ysfFormItems222"
                >
                </zj-form-module>
                <zj-form-module
                  v-if="formData.couponType === 'GOODS'"
                  title="指定商品"
                  label-width="120px"
                  :form-data="formData"
                  :form-items="xzspFormItems"
                >
                </zj-form-module>
              </zj-form-container>
            </div>
          </zj-page-fill>
          <div
            style="
              text-align: right;
              box-sizing: border-box;
              padding: 16px 20px;
            "
          >
            <el-button size="mini" @click="handleClose">取消</el-button>
            <el-button
              v-if="!xiangqing"
              size="mini"
              type="primary"
              @click="save"
              >保存</el-button
            >
          </div>
        </zj-page-container>
      </el-dialog>
    </div>
  </template-page>
</template>

<script>
import TemplatePage from "@/components/template/template-page-1.vue";
import import_mixin from "@/components/template/import_mixin.js";
import operation_mixin from "@/components/template/operation_mixin.js";
import {
  couponList,
  couponListExport,
  couponAdd,
  couponUpdate,
  couponDetail,
  couponCancel,
} from "@/api/coupon2.js";
import { required } from "@/components/template/rules_verify.js";
import ImageUpload from "@/components/file-upload";
import pagingTransfer from "@/components/paging-transfer.vue";
import { EventBus } from "@/utils/eventBus";
import { getMemberList } from "@/api/member";
import { getGoodsList } from "@/api/goods";
import { adminCompanyList } from "@/api/payingMerchant.js";
import { adminWebsitList } from "@/api/merchantManagement.js";
export default {
  components: { TemplatePage, ImageUpload, pagingTransfer },
  mixins: [import_mixin, operation_mixin],
  data() {
    return {
      pageType: "list",
      pageShow: true,
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false,
      },
      // 表格事件
      tableEvents: {
        "selection-change": this.selectionChange,
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialog: false,
      formData: {
        activeDay: "",
        activeEndTime: "",
        activeStartTime: "",
        activeType: "",
        companyName: "",
        companyWechatId: "",
        couponAmount: "",
        couponId: "",
        couponName: "",
        couponType: "SATISFY",
        couponValue: "",
        createBy: "",
        createTime: "",
        displayTime: "",
        flag: "",
        goodsList: [],
        imgSrc: [],
        leftAmount: "",
        note: "",
        obtainEndTime: "",
        obtainStartTime: "",
        orderAmount: "",
        originalPriceLimit: "",
        receiveAmount: "",
        receiveCrowd: "",
        receiveLimitCount: "",
        releaseEndTime: "",
        releaseStartTime: "",
        remark: "",
        shareTimes: "",
        sortNum: "",
        tagList: [],
        transferType: "",
        type: [0, 1, 3].includes(
          JSON.parse(localStorage.getItem("greemall_user"))?.type
        )
          ? "A"
          : "B",

        updateBy: "",
        updateTime: "",
        userList: [],
        couponCompanyList: [0, 1, 3].includes(
          JSON.parse(localStorage.getItem("greemall_user"))?.type
        )
          ? []
          : [JSON.parse(localStorage.getItem("greemall_user"))?.companyId],
        couponWebsitList: [],
      },
      xiangqing: false,
      formInline: {
        keyword: "",
      },
      formInlineSP: {
        keywordSP: "",
      },
      zzdshangji: [],
      wangduainshu: [],
    };
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth("add", {
              click: this.openForm,
            }),
          ],
        ],
      ];
    },
    // 更多参数
    moreParameters() {
      return [];
    },
    formItems() {
      return [
        {
          md: 6,
          isShow: true,
          name: "el-radio",
          options: [
            { label: "平台券", value: "A" },
            { label: "商家券", value: "B" },
          ],
          attributes: {
            disabled: true,
          },
          formItemAttributes: {
            label: "优惠券性质",
            prop: "type",
            rules: [...required],
          },
          events: {
            change: (v) => {
              if (
                v == "B" &&
                JSON.parse(localStorage.getItem("greemall_user"))?.companyId
              ) {
                this.formData.couponCompanyList = [
                  JSON.parse(localStorage.getItem("greemall_user"))?.companyId,
                ];
                this.formData.couponWebsitList = [];
                this.formData.userList = [];
                EventBus.$emit("handlePaginaXXPPPBack22");
              }
            },
          },
        },

        {
          isShow: true,
          name: "el-input",
          md: 12,
          attributes: {
            disabled: this.xiangqing,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "优惠券名称",
            prop: "couponName",
            rules: [...required],
          },
        },
        {
          md: 6,
          isShow: true,
          name: "el-radio",
          options: [
            { label: "满减券", value: "SATISFY" },
            { label: "商品券", value: "GOODS" },
          ],
          attributes: {
            disabled: this.xiangqing,
          },
          formItemAttributes: {
            label: "优惠券类型",
            prop: "couponType",
            rules: [...required],
          },
          events: {
            change: (v) => {
              if (v !== "GOODS") {
                this.formInlineSP.keywordSP = "";
                this.formData.goodsList = [];
              }
            },
          },
        },

        {
          isShow: this.formData.couponType == "SATISFY",
          name: "el-input",
          md: 6,
          attributes: {
            disabled: this.xiangqing,
            placeholder: "请输入",
            type: "number",
          },
          formItemAttributes: {
            label: "订单满足金额",
            prop: "orderAmount",
            rules: [...required],
          },
        },

        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: this.xiangqing,
            placeholder: "请输入",
            type: "number",
          },
          formItemAttributes: {
            label: "优惠券面值",
            prop: "couponValue",
            rules: [...required],
          },
          events: {
            input: (v) => {
              this.formData.couponValue = Number(v) < 0 ? 0 : Number(v);
            },
          },
        },

        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: this.xiangqing,
            placeholder: "请输入",
            type: "number",
          },
          formItemAttributes: {
            label: "发放总数量",
            prop: "couponAmount",
            rules: [...required],
          },
        },

        {
          isShow: true,
          name: "el-input",
          md: 6,
          attributes: {
            disabled: this.xiangqing,
            placeholder: "请输入",
            type: "number",
          },
          formItemAttributes: {
            label: "每人限领数量",
            prop: "receiveLimitCount",
            rules: [...required],
          },
        },

        // {
        //   isShow: true,
        //   name: "el-date-picker",
        //   md: 6,
        //   attributes: {
        //     "append-to-body": true,
        //     disabled: this.xiangqing,
        //     style: { width: "100%" },
        //     type: "datetime",
        //     placeholder: "请选择",
        //     "value-format": "yyyy-MM-dd HH:mm:ss",
        //     "picker-options": {},
        //   },
        //   events: {
        //     change: (value) => {},
        //   },
        //   formItemAttributes: {
        //     label: "显示时间",
        //     prop: "displayTime",
        //     rules: [...required],
        //   },
        // },

        {
          md: 24,
          isShow: true,
          name: "slot-component",
          formItemAttributes: {
            label: "",
            prop: "",
            rules: [],
          },
          render: (h, { props, onInput }) => {
            return null;
          },
        },

        {
          isShow: true,
          name: "el-date-picker",
          md: 6,
          attributes: {
            "append-to-body": true,
            disabled: this.xiangqing,
            style: { width: "100%" },
            type: "date",
            placeholder: "请选择",
            "value-format": "yyyy-MM-dd HH:mm:ss",
            "picker-options": {},
          },
          events: {
            change: (value) => {
              this.formData.obtainEndTime = "";
            },
          },
          formItemAttributes: {
            label: "可领取开始时间",
            prop: "obtainStartTime",
            rules: [...required],
          },
        },
        {
          isShow: true,
          name: "el-date-picker",
          md: 6,
          attributes: {
            "append-to-body": true,
            disabled: this.xiangqing || !this.formData.obtainStartTime,
            style: { width: "100%" },
            type: "date",
            placeholder: "请选择",
            "value-format": "yyyy-MM-dd HH:mm:ss",
            "picker-options": {
              disabledDate: (time) => {
                return (
                  time.getTime() <
                  new Date(this.formData.obtainStartTime).getTime()
                );
              },
            },
          },
          events: {
            change: (value) => {},
          },
          formItemAttributes: {
            label: "可领取结束时间",
            prop: "obtainEndTime",
            rules: [...required],
          },
        },

        // {
        //   isShow: true,
        //   name: "el-input",
        //   md: 12,
        //   attributes: {
        //     disabled: this.xiangqing,
        //     placeholder: "请输入",
        //     type: "number",
        //   },
        //   formItemAttributes: {
        //     label: "有效时间",
        //     prop: "activeDay",
        //     rules: [],
        //   },
        //   slots: {
        //     prepend: (h, { props, onInput }) => {
        //       return <span>领券后</span>;
        //     },

        //     append: (h, { props, onInput }) => {
        //       return <span>天内有效</span>;
        //     },
        //   },
        // },

        {
          md: 24,
          isShow: true,
          name: "slot-component",
          formItemAttributes: {
            label: "",
            prop: "",
            rules: [],
          },
          render: (h, { props, onInput }) => {
            return null;
          },
        },

        {
          isShow: true,
          name: "el-date-picker",
          md: 6,
          attributes: {
            "append-to-body": true,
            disabled: this.xiangqing,
            style: { width: "100%" },
            type: "date",
            placeholder: "请选择",
            "value-format": "yyyy-MM-dd HH:mm:ss",
            "picker-options": {},
          },
          events: {
            change: (value) => {
              this.formData.activeEndTime = "";
            },
          },
          formItemAttributes: {
            label: "可使用开始时间",
            prop: "activeStartTime",
            rules: [],
          },
        },

        {
          isShow: true,
          name: "el-date-picker",
          md: 6,
          attributes: {
            "append-to-body": true,
            disabled: this.xiangqing || !this.formData.activeStartTime,
            style: { width: "100%" },
            type: "date",
            placeholder: "请选择",
            "value-format": "yyyy-MM-dd HH:mm:ss",
            "picker-options": {
              disabledDate: (time) => {
                return (
                  time.getTime() <
                  new Date(this.formData.activeStartTime).getTime()
                );
              },
            },
          },
          events: {
            change: (value) => {},
          },
          formItemAttributes: {
            label: "可使用结束时间",
            prop: "activeEndTime",
            rules: [],
          },
        },

        {
          isShow: true,
          name: "el-input",
          md: 24,
          attributes: {
            disabled: this.xiangqing,
            type: "textarea",
            rows: 2,
            placeholder: "请输入",
          },
          formItemAttributes: {
            label: "使用说明",
            prop: "note",
            rules: [...required],
          },
        },

        // {
        //   md: 24,
        //   isShow: true,
        //   name: "slot-component",
        //   formItemAttributes: {
        //     label: "首页弹窗图片",
        //     prop: "imgSrc",
        //     rules: [],
        //   },
        //   render: (h, { props, onInput }) => {
        //     var { value } = props;
        //     return (
        //       <ImageUpload
        //         fileList={this.formData.imgSrc}
        //         uid="imgSrc666_materials_sjdjfking_images"
        //         limit={1}
        //         isEdit={!this.xiangqing}
        //       />
        //     );
        //   },
        // },
        {
          isShow: true,
          name: "el-select",
          md: 12,
          options: this.zzdshangji,
          attributes: {
            disabled: this.xiangqing || this.formData.type == "B",
            placeholder: "请选择",
            clearable: true,
            filterable: true,
            multiple: true,
          },
          formItemAttributes: {
            label: "下发商户",
            prop: "couponCompanyList",
            rules: [...required],
          },
          events: {
            change: (val) => {
              this.formData.couponWebsitList = [];
              this.formData.userList = [];
              EventBus.$emit("handlePaginaXXPPPBack22");
            },
          },
        },
        {
          isShow: true,
          name: "el-select",
          md: 12,
          options: this.wangduainshu.filter((item) =>
            this.formData.couponCompanyList.includes(item.companyId)
          ),
          attributes: {
            disabled: this.xiangqing,
            placeholder: "请选择",
            clearable: true,
            filterable: true,
            multiple: true,
          },
          formItemAttributes: {
            label: "下发商家",
            prop: "couponWebsitList",
            rules: this.formData.type == "B" ? [...required] : [],
          },
          events: {
            change: (val) => {
              this.formData.userList = [];
              EventBus.$emit("handlePaginaXXPPPBack22");
            },
          },
        },
        {
          md: 24,
          isShow: true,
          name: "el-radio",
          options: [
            { label: "所有用户", value: 0 },
            { label: "所有普通用户", value: 4 },
            { label: "所有分销员", value: 3 },
            { label: "指定用户", value: 2 },
          ],
          attributes: {
            disabled: this.xiangqing,
          },
          formItemAttributes: {
            label: "领取条件",
            prop: "receiveCrowd",
            rules: [...required],
          },
        },
      ];
    },
    ysfFormItems() {
      return [
        {
          isShow: this.formData.receiveCrowd === 2,
          name: "slot-component",
          md: 24,
          attributes: {},
          formItemAttributes: {
            label: "",
            "label-width": "0px",
            prop: "userList",
            rules: [...required],
          },
          render: (h, { props, onInput }) => {
            var { formData } = props;

            return (
              <div key="handlePaginaXXPPPBack22">
                <div>
                  <el-form
                    size="mini"
                    inline={true}
                    value={this.formInline}
                    onInput={(v) => {
                      this.formInline = v;
                    }}
                    label-width="0px"
                  >
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.keyword}
                        onInput={(v) => {
                          this.formInline.keyword = v;
                        }}
                        placeholder="名称/电话"
                      ></el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button
                        type="primary"
                        onClick={() => {
                          EventBus.$emit("handlePaginaXXPPPBack22");
                        }}
                      >
                        查询
                      </el-button>
                      <el-button
                        onClick={() => {
                          this.formInline.keyword = "";
                          this.$nextTick(() => {
                            EventBus.$emit("handlePaginaXXPPPBack22");
                          });
                        }}
                      >
                        重置
                      </el-button>
                    </el-form-item>
                  </el-form>
                </div>
                <pagingTransfer
                  handlePaginationCallBackKey="handlePaginaXXPPPBack22"
                  value={this.formData.userList}
                  onInput={(v) => {
                    this.formData.userList = v;
                  }}
                  left-columns={[
                    {
                      id: "avatar",
                      label: "头像",
                      width: "160",
                      showType: "img",
                    },
                    { id: "nickName", label: "名称", width: "120" },
                    { id: "mobile", label: "电话", width: "" },
                    { id: "sex", label: "性别", width: "" },
                    {
                      id: "type",
                      label: "角色",
                      width: "",
                      convert: { GENERAL: "普通用户", SERVICE: "业务员" },
                    },
                  ]}
                  right-columns={[
                    {
                      id: "avatar",
                      label: "头像",
                      width: "160",
                      showType: "img",
                    },
                    { id: "nickName", label: "名称", width: "120" },
                    { id: "mobile", label: "电话", width: "" },
                    { id: "sex", label: "性别", width: "" },
                    {
                      id: "type",
                      label: "角色",
                      width: "",
                      convert: { GENERAL: "普通用户", SERVICE: "业务员" },
                    },
                  ]}
                  show-pagination={true}
                  pagination-call-back={this.paginationCallback}
                  title-texts={["待选项", "已选项"]}
                  min-height="300px"
                  table-row-key={(row) => row.userId}
                />
              </div>
            );
          },
        },
      ];
    },
    ysfFormItems222() {
      return [
        {
          isShow: this.formData.receiveCrowd === 2,
          name: "slot-component",
          md: 24,
          attributes: {},
          formItemAttributes: {
            label: "",
            "label-width": "0px",
            prop: "userList",
            rules: [...required],
          },
          render: (h, { props, onInput }) => {
            var { formData } = props;
            return (
              <div key="handlePaginaXXPPPBack22">
                <div>
                  <el-form
                    size="mini"
                    inline={true}
                    value={this.formInline}
                    onInput={(v) => {
                      this.formInline = v;
                    }}
                    label-width="0px"
                  >
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.keyword}
                        onInput={(v) => {
                          this.formInline.keyword = v;
                        }}
                        placeholder="名称/电话"
                      ></el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button
                        type="primary"
                        onClick={() => {
                          EventBus.$emit("handlePaginaXXPPPBack22");
                        }}
                      >
                        查询
                      </el-button>
                      <el-button
                        onClick={() => {
                          this.formInline.keyword = "";
                          this.$nextTick(() => {
                            EventBus.$emit("handlePaginaXXPPPBack22");
                          });
                        }}
                      >
                        重置
                      </el-button>
                    </el-form-item>
                  </el-form>
                </div>
                <pagingTransfer
                  handlePaginationCallBackKey="handlePaginaXXPPPBack22"
                  value={this.formData.userList}
                  onInput={(v) => {
                    this.formData.userList = v;
                  }}
                  left-columns={[
                    {
                      id: "avatar",
                      label: "头像",
                      width: "160",
                      showType: "img",
                    },
                    { id: "nickName", label: "名称", width: "120" },
                    { id: "mobile", label: "电话", width: "" },
                    { id: "sex", label: "性别", width: "" },
                    {
                      id: "type",
                      label: "角色",
                      width: "",
                      convert: { GENERAL: "普通用户", SERVICE: "业务员" },
                    },
                  ]}
                  right-columns={[
                    {
                      id: "avatar",
                      label: "头像",
                      width: "160",
                      showType: "img",
                    },
                    { id: "nickName", label: "名称", width: "120" },
                    { id: "mobile", label: "电话", width: "" },
                    { id: "sex", label: "性别", width: "" },
                    {
                      id: "type",
                      label: "角色",
                      width: "",
                      convert: { GENERAL: "普通用户", SERVICE: "业务员" },
                    },
                  ]}
                  show-pagination={true}
                  pagination-call-back={this.paginationCallback}
                  title-texts={["待选项", "已选项"]}
                  min-height="300px"
                  table-row-key={(row) => row.userId}
                />
              </div>
            );
          },
        },
      ];
    },
    xzspFormItems() {
      return [
        {
          isShow: this.formData.couponType === "GOODS",
          name: "slot-component",
          md: 24,
          attributes: {},
          formItemAttributes: {
            label: "",
            "label-width": "0px",
            prop: "goodsList",
            rules: [...required],
          },
          render: (h, { props, onInput }) => {
            var { formData } = props;
            if (this.xiangqing) {
              return (
                <zj-table
                  columns={[
                    {
                      columnAttributes: {
                        label: "商品名称",
                        prop: "goodsName",
                      },
                    },
                  ]}
                  table-data={this.formData.goodsList}
                />
              );
            }
            if (this.formData.couponType === "GOODS") {
              return (
                <div key="handlefghjhjbnlihPPPBack22">
                  <div>
                    <el-form
                      size="mini"
                      inline={true}
                      value={this.formInlineSP}
                      onInput={(v) => {
                        this.formInlineSP = v;
                      }}
                      label-width="0px"
                    >
                      <el-form-item label="">
                        <el-input
                          value={this.formInlineSP.keywordSP}
                          onInput={(v) => {
                            this.formInlineSP.keywordSP = v;
                          }}
                          placeholder="商品名称"
                        ></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button
                          type="primary"
                          onClick={() => {
                            EventBus.$emit("handlefghjhjbnlihPPPBack22");
                          }}
                        >
                          查询
                        </el-button>
                        <el-button
                          onClick={() => {
                            this.formInlineSP.keywordSP = "";
                            this.$nextTick(() => {
                              EventBus.$emit("handlefghjhjbnlihPPPBack22");
                            });
                          }}
                        >
                          重置
                        </el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                  <pagingTransfer
                    handlePaginationCallBackKey="handlefghjhjbnlihPPPBack22"
                    value={this.formData.goodsList}
                    onInput={(v) => {
                      this.formData.goodsList = v;
                    }}
                    left-columns={[
                      { id: "goodsName", label: "商品名称", width: "" },
                      { id: "goodsPrice", label: "商品价格", width: "100" },
                      { id: "stockNum", label: "商品库存", width: "100" },
                    ]}
                    right-columns={[
                      { id: "goodsName", label: "商品名称", width: "" },
                    ]}
                    show-pagination={true}
                    pagination-call-back={this.paginationCallbackSp}
                    title-texts={["待选项", "已选项"]}
                    min-height="300px"
                    table-row-key={(row) => row.goodsId}
                  />
                </div>
              );
            } else {
              this.formInlineSP.keywordSP = "";
              this.formData.goodsList = [];
              return null;
            }
          },
        },
      ];
    },
  },
  methods: {
    paginationCallbackSp({ pageIndex, pageSize }) {
      return new Promise((resolve) => {
        let params = {
          keyword: this.formInlineSP.keywordSP,
          status: true,
          pageNum: pageIndex,
          pageSize: pageSize,
        };
        getGoodsList(params).then((res) => {
          resolve({
            total: res.data.total,
            data: res.data.records,
          });
        });
      });
    },
    paginationCallback({ pageIndex, pageSize }) {
      return new Promise((resolve) => {
        let params = {
          keyword: this.formInline.keyword,
          pageNum: pageIndex,
          pageSize: pageSize,
          companyIds: this.formData.couponCompanyList?.join(",") || "",
          websitIds: this.formData?.couponWebsitList?.join(",") || "",
        };
        getMemberList(params).then((res) => {
          resolve({
            total: res.data.total,
            data: res.data.records,
          });
        });
      });
    },
    // 列表请求函数
    getList: couponList,
    // 列表导出函数
    exportList: couponListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData;
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data;
    },
    // 打开创建弹窗
    openForm() {
      Promise.all([
        adminCompanyList({
          pageNum: 1,
          pageSize: -1,
          params: [],
        }),
        adminWebsitList({
          pageNum: 1,
          pageSize: -1,
          params: [{ param: "status", compare: "=", value: "ON" }],
        }),
      ]).then(([res1, res2]) => {
        this.zzdshangji = res1.data.records.map((item) => ({
          label: item.adminCompanyName,
          value: item.adminCompanyId,
        }));
        this.wangduainshu = res2.data.records.map((item) => ({
          value: item.websitId,
          label: item.name,
          companyId: item.companyId,
        }));
        this.formDialog = true;
      });
    },
    // 打开详情弹窗
    openDetailForm(row, cb) {
      Promise.all([
        couponDetail({ couponId: row.couponId }),
        adminCompanyList({
          pageNum: 1,
          pageSize: -1,
          params: [],
        }),
        adminWebsitList({
          pageNum: 1,
          pageSize: -1,
          params: [{ param: "status", compare: "=", value: "ON" }],
        }),
      ]).then(([res, res1, res2]) => {
        this.formData = {
          ...res.data,
          imgSrc: res.data.imgSrc ? [{ imgSrc: res.data.imgSrc }] : [],
          couponWebsitList: res.data.couponWebsitList.map(
            (item) => item.websitId
          ),
          couponCompanyList: res.data.couponCompanyList.map(
            (item) => item.companyId
          ),
        };
        this.zzdshangji = res1.data.records.map((item) => ({
          label: item.adminCompanyName,
          value: item.adminCompanyId,
        }));
        this.wangduainshu = res2.data.records.map((item) => ({
          value: item.websitId,
          label: item.name,
          companyId: item.companyId,
        }));
        this.formDialog = true;
        cb?.();
      });
    },
    handleClose() {
      this.$refs?.formRef?.resetFields();
      this.$data.formData = this.$options.data().formData;
      this.formDialog = false;
      this.xiangqing = false;
    },
    // 操作按钮
    operation() {
      return this.operationBtn({
        edit: {
          click: ({ row, index, column }) => {
            this.openDetailForm(row);
          },
        },
        details: {
          click: ({ row, index, column }) => {
            this.openDetailForm(row, () => {
              this.xiangqing = true;
            });
          },
        },
        cancel: {
          conditions: ({ row, index, column }) => {
            return ["START", "WAIT"].includes(row.flag);
          },
          click: ({ row, index, column }) => {
            couponCancel({ couponId: row.couponId }).then((res) => {
              this.$message({
                type: "success",
                message: "取消成功",
              });
              this.$refs.pageRef.refreshList();
            });
          },
        },
      });
    },
    // 保存
    save() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          (this.formData?.couponId ? couponUpdate : couponAdd)({
            ...this.formData,
            imgSrc:
              this.formData.imgSrc && this.formData.imgSrc.length
                ? this.formData.url?.[0]?.imgSrc
                : "",
            couponWebsitList: this.formData.couponWebsitList.map(
              (websitId) => ({
                websitId: websitId,
                websitName: this.wangduainshu?.find(
                  (val) => val.value === websitId
                )?.label,
              })
            ),
            couponCompanyList: this.formData.couponCompanyList.map(
              (companyId) => ({
                companyId: companyId,
                companyName: this.zzdshangji?.find(
                  (val) => val.value === companyId
                )?.label,
              })
            ),
            activeEndTime: this.formData.activeEndTime
              ? this.formData.activeEndTime.split(" ")[0] + " 23:59:59"
              : "",
            obtainEndTime: this.formData.obtainEndTime
              ? this.formData.obtainEndTime.split(" ")[0] + " 23:59:59"
              : "",
          }).then((res) => {
            this.$message({
              type: "success",
              message: "保存成功",
            });
            this.handleClose();
            this.$refs.pageRef.refreshList();
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
