<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchFunc="queryhFunc" :resetFunc="onReset">
        <jeepay-text-up v-model:value="vdata.searchData.packageName" :placeholder="'方案名称'"
          :msg="vdata.searchData.packageName" />
        <jeepay-text-up v-model:value="vdata.searchData.typeName" :placeholder="'方案分类'"
                        :msg="vdata.searchData.typeName" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData['packageState']" placeholder="状态">
            <a-select-option :value="''">全部</a-select-option>
            <a-select-option :value="1">已上架</a-select-option>
            <a-select-option :value="0">已下架</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData['charge']" placeholder="是否收费">
            <a-select-option :value="1">是</a-select-option>
            <a-select-option :value="0">否</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData['audit']" placeholder="是否审核">
            <a-select-option :value="1">是</a-select-option>
            <a-select-option :value="0">否</a-select-option>
          </a-select>
        </a-form-item>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable ref="infoTable" :init-data="true" :req-table-data-func="reqTableDataFunc" :table-columns="tableColumns"
        :search-data="vdata.searchData" @btnLoadClose="vdata.btnLoading = false">
        <template #topBtnSlot>
          <div>
            <a-button v-if="$access('ENT_NOTICE_ADD')" type="primary" class="mg-b-30" @click="addNewNotice">
              <plus-outlined />新建
            </a-button>
          </div>
        </template>
        <template #bodyCell="{ column, record }">


          <template v-if="column.key === 'charge'">
            <a-badge v-if="record.charge == 1" status="success" text="是" />
            <a-badge v-if="record.charge == 0" status="error" text="否" />
          </template>
          <template v-if="column.key === 'audit'">
            <a-badge v-if="record.audit == 1" status="success" text="是" />
            <a-badge v-if="record.audit == 0" status="error" text="否" />
          </template>

          <template v-if="column.key === 'packageState'">
            <JeepayTableColState :state="record.packageState" :showSwitchType="$access('ENT_DEVICE_QRC_EDIT')" :onChange="(productState) => { return updateState(record.packageId, productState)}" />
          </template>

          <template v-if="column.key === 'op'">
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_NOTICE_EDIT')" type="link" @click="editFunc(record)">修改</a-button>
              <a-button v-if="$access('ENT_NOTICE_DEL')" type="link" style="color:red"
                @click="delFunc(record.packageId)">删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>
    <!-- 日志详情抽屉 -->
    <template>
      <a-drawer width="50%" placement="right" :closable="true" :visible="visible" :maskClosable="false"
        :title="vdata.isAdd ? '新建方案' : '方案详情'" :destroyOnClose="true" @close="onClose">
        <div class="account-settings-info-view">
          <a-form ref="infoFormModel" layout="vertical" :model="vdata.noticeDate" :rules="saveRule">
            <a-row >
              <p class="jee-drawer-title">基础信息配置</p>
              <a-col :span="24">
                <a-form-item label="方案类型" name="packageSpecs">
                  <!-- <a-radio-group v-model:value="vdata.noticeDate.packageType">
                    <a-radio :value="1">接口型</a-radio>
                    <a-radio :value="0">服务型</a-radio>
                  </a-radio-group> -->
                  <a-checkbox-group v-model:value="vdata.noticeDate.packageSpecs">
                    <a-checkbox v-for="option in vdata.plainOptions" :key="option" :value="option.lable">
                      {{ option.name }}
                    </a-checkbox>
                  </a-checkbox-group>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="方案状态" name="packageState">
                  <a-radio-group v-model:value="vdata.noticeDate.packageState" :defaultValue="1">
                    <a-radio :value="1"> 已上架 </a-radio>
                    <a-radio :value="0"> 已下架 </a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="方案logo" name="packageLogoUrl">
                  <JeepayUpload v-model:src="vdata.noticeDate.packageLogoUrl" bizType="oem" />
                  <span class="jeepay-tip-text">建议最小尺寸：220*220px，不超过2.9M</span>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="方案名称" name="name">
                  <a-input v-model:value="vdata.noticeDate.name" placeholder="方案名称" />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="方案排序" name="packageSort">
                  <a-input v-model:value="vdata.noticeDate.packageSort" placeholder="请输入方案排序" />
                  <span style="font-size: smaller;color: crimson;">从小到大排序。</span>
                </a-form-item>
              </a-col>

              <a-col :span="24">
                <a-form-item label="选择分类" name="typeName">
                  <a-select show-search :value="vdata.noticeDate.typeName" placeholder="选择分类" @change="changeFunc">
                    <a-select-option v-for="(item) in vdata.packageTypeList" :key="item.typeId" :value="item.typeName">
                      {{ item.typeName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>




<!--              <a-col :span="11">-->
<!--                <a-form-item label="方案金额" name="price">-->
<!--                  <a-input-number v-model:value="vdata.noticeDate.price" placeholder="请输入方案金额" style="width:100%" />-->
<!--                </a-form-item>-->
<!--              </a-col>-->
              <a-col :span="24">
                <a-form-item label="方案文档地址" name="packageUrl">
                  <a-input v-model:value="vdata.noticeDate.packageUrl" placeholder="方案文档地址" />
                </a-form-item>
              </a-col>


              <a-col :span="24" style="margin:10px 0px">
<!--                <a-collapse>-->
<!--                  <a-collapse-panel header="关联产品配置">-->
<!--                    <a-form-item :label="'关联产品'" name="productIds" class="collapse-div">-->
<!--                      <a-checkbox-group v-model:value="vdata.noticeDate.productIds">-->
<!--                        <a-checkbox v-for="(value) in vdata.productArrList" :key="value.productId"-->
<!--                          :value="value.productId">{{ value.productName }}</a-checkbox>-->
<!--                      </a-checkbox-group>-->
<!--                    </a-form-item>-->
<!--                  </a-collapse-panel>-->
<!--                </a-collapse>-->
                <a-form-item label="关联产品配置" name="productIds">
                  <a-textarea v-if="vdata.noticeDate.productIdsName" v-model:value="vdata.noticeDate.productIdsName"
                              disabled />
                  <a-button style="margin-top: 5px" type="primary" @click="showQrcSelectProductModel">{{
                      vdata.isAdd ?
                          '选择绑定产品' : '重新绑定产品' }}</a-button>
                </a-form-item>
              </a-col>
              <a-col :span="24" style="margin:10px 0px">
<!--                <a-collapse>-->
<!--                  <a-collapse-panel header="关联方案配置">-->
<!--                    <a-form-item :label="'关联方案'" name="packageIds" class="collapse-div">-->
<!--                      <a-checkbox-group v-model:value="vdata.noticeDate.packageIds">-->
<!--                        <a-checkbox v-for="(value, index) in vdata.packageList" :key="index" :value="value.packageId">{{-->
<!--                          value.name }}</a-checkbox>-->
<!--                      </a-checkbox-group>-->
<!--                    </a-form-item>-->
<!--                  </a-collapse-panel>-->
<!--                </a-collapse>-->
                <a-form-item label="关联方案配置" name="packageName">
                  <a-textarea v-if="vdata.noticeDate.packageName" v-model:value="vdata.noticeDate.packageName" disabled />
                  <a-button style="margin-top: 5px" type="primary" @click="showQrcSelectPackageModel">{{
                      vdata.isAdd ?
                          '选择绑定方案' : '重新绑定方案' }}</a-button>
                </a-form-item>
              </a-col>
              <a-col :span="24" style="margin:10px 0px">
<!--                <a-collapse>-->
<!--                  <a-collapse-panel header="关联通道配置">-->
<!--                    <a-checkbox-group name="payInterfaceCodes" v-model:value="vdata.noticeDate.payInterfaceCodes">-->
<!--                      <a-checkbox v-for="(item, key) in vdata.IfDefinesList" :key="key" :value="item.ifCode">{{-->
<!--                        item.ifName-->
<!--                      }}</a-checkbox>-->
<!--                    </a-checkbox-group>-->
<!--                  </a-collapse-panel>-->
<!--                </a-collapse>-->
                <a-form-item label="关联通道配置" name="payInterfaceName">
                  <a-textarea v-if="vdata.noticeDate.payInterfaceName" v-model:value="vdata.noticeDate.payInterfaceName"
                              disabled />
                  <a-button style="margin-top: 5px" type="primary" @click="showQrcSelectPayInterfaceModel">{{
                      vdata.isAdd
                          ? '选择绑定通道' : '重新绑定通道' }}</a-button>
                </a-form-item>
              </a-col>

              <p class="jee-drawer-title">方案内容配置</p>
              <a-col :span="24">
                <a-form-item label="方案描述" name="desc">
                  <a-textarea v-model:value="vdata.noticeDate.desc" placeholder="方案描述" :rows="3" />
                </a-form-item>
              </a-col><br />
              <a-col :span="24">
                <a-form-item label="方案内容" name="">
                  <div style="border: 1px solid #ccc">
                    <!-- 工具栏 -->
                    <Toolbar :editorId="editorId" :defaultConfig="toolbarConfig" style="border-bottom: 1px solid #ccc" />
                    <!-- 编辑器 -->
                    <Editor :defaultHtml="vdata.content" :editorId="editorId" :defaultConfig="editorConfig"
                      style="height: 350px; overflow-y: hidden;" />
                  </div>
                </a-form-item>
              </a-col>
<!--              <a-col :span="24">-->
<!--                <a-form-item label="收费信息" name="">-->
<!--                  <div style="border: 1px solid #ccc">-->
<!--                    &lt;!&ndash; 工具栏 &ndash;&gt;-->
<!--                    <Toolbar :editorId="editorId3" :defaultConfig="toolbarConfig" style="border-bottom: 1px solid #ccc" />-->
<!--                    &lt;!&ndash; 编辑器 &ndash;&gt;-->
<!--                    <Editor :defaultHtml="vdata.text" :editorId="editorId3" :defaultConfig="editorConfig3"-->
<!--                      style="height: 350px; overflow-y: hidden;" />-->
<!--                  </div>-->
<!--                </a-form-item>-->
<!--              </a-col>-->


              <a-col :span="24" style="margin:10px 0px">
                <a-form-item label="是否收费" name="charge">
                  <a-radio-group v-model:value="vdata.noticeDate.charge">
                    <a-radio :value="1">是</a-radio>
                    <a-radio :value="0">否</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-table bordered :data-source="vdata.feeDataSource" :columns="vdata.feeColumns"
                  v-if="vdata.noticeDate.charge === 1" :pagination="false" style="margin-left: -1px;">
                  <template #versionName="{ record }">
                    <a-input v-model:value="record['versionName']" />
                  </template>
                  <template #validTime="{ record }">
                    <a-input-number addon-after="天" :min="1" v-model:value="record['validTime']" />
                  </template>
                  <template #sellingPrice="{ record }">
                    <a-input-number addon-after="元" v-model:value="record['sellingPrice']" :precision="2" :min="0"
                      :step="0.01" />
                  </template>
                  <template #lineationPrice="{ record }">
                    <a-input-number addon-after="元" v-model:value="record['lineationPrice']" :precision="2" :min="0"
                      :step="0.01" />
                  </template>
                  <template #operation="{ record }">
                    <a-popconfirm v-if="vdata.feeDataSource.length" title="确认删除吗?" @confirm="onDelete(record.key)">
                      <a style="margin-right: 20px;">删除</a>
                    </a-popconfirm>
                    <a @click="onAdd">添加</a>
                  </template>
                </a-table>
              </a-col>
              <a-col :span="24" style="margin:10px 0px">
                <a-form-item label="是否审核" name="audit">
                  <a-radio-group v-model:value="vdata.noticeDate.audit">
                    <a-radio :value="1">是</a-radio>
                    <a-radio :value="0">否</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-divider class="jeepay-m-divider" orientation="left" style="font-weight: 900;"><span
                  style="margin-left: -60px;">特殊资质</span></a-divider>
              <a-col :span="24" style="margin:10px 0px">
                <a-form-item label="是否需要特殊资质" name="certification">
                  <a-radio-group v-model:value="vdata.noticeDate.certification">
                    <a-radio :value="1">是</a-radio>
                    <a-radio :value="0">否</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="24" style="margin:10px 0px" v-if="vdata.noticeDate.certification === 1">
                <a-button class="editable-add-btn" style="margin-bottom: 8px;margin-left: -1px;" type="dashed"
                  @click="handleAdd">
                  <PlusOutlined />新增
                </a-button>
                <a-table bordered :data-source="vdata.certificationDataSource" :columns="vdata.certificationColumns"
                  style="margin-left: -1px;">
                  <template #headerCell="{ title, column }">
                    <a-tooltip v-if="column.ellipsis" :title="title"
                      :overlayStyle="{ whiteSpace: 'nowrap', maxWidth: '1000px' }">
                      {{ title }}
                    </a-tooltip>
                    <div v-else>{{ title }}</div>
                  </template>
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'certificationUrl'">
                      <div>
                        <a-radio-group v-model:value="record.inputType">
                          <a-radio value="file"> 示例图 </a-radio>
                          <!--                    <a-radio value="text"> 文本 </a-radio>-->
                        </a-radio-group>
                      </div>
                      <div class="editable-cell" v-if="record.inputType == 'file'">
                        <div class="editable-cell-input-wrapper">
                          <JeepayUpload v-model:src="record.certificationUrl" bizType="notice" listType="picture-card" />
                        </div>
                      </div>
                    </template>
                    <template v-else-if="column.dataIndex === 'certificationName'">
                      <div class="editable-cell-input-wrapper">
                        <a-input v-model:value="record.certificationName" />
                      </div>
                    </template>
                    <template v-else-if="column.dataIndex === 'operation'">
                      <a style="color: red" @click="certificationOnDelete(record.key)">删除</a>
                    </template>
                  </template>
                </a-table>
              </a-col>

              <a-form-item class="bottom-btn" style="margin-top: 20px">
                <a-button type="primary" :loading="vdata.btnLoading" @click="confirm">
                  <check-circle-outlined />{{ vdata.isAdd ? '确认新建' : '确认更新' }}
                </a-button>
              </a-form-item>
            </a-row>
          </a-form>
        </div>
      </a-drawer>
    </template>
  </page-header-wrapper>
  <JeepayNoticeViewer ref="noticeViewer" />

  <JeepayModelProductList v-if="JeepayModelProductListFlag" ref="jeepayModelProductListRef" @selectFinishFunc="selectQrcFinishProductFunc" />
  <JeepayModelProgrammeList v-if="jeepayModelProgrammeListFlag" ref="jeepayModelProgrammeListRef"
                            @selectFinishFunc="selectQrcFinishPackageFunc" :title="vdata.title" />
  <JeepayModelPayInterfaceList v-if="JeepayModelPayInterfaceListFlag" ref="jeepayModelPayInterfaceListRef"
                               @selectFinishFunc="selectQrcFinishPayInterfaceFunc" />
</template>

<script setup lang="ts">
import {
  API_URL_PRODUCT_LIST,
  req,
  $getUploadFormParams,
  API_URL_PRODUCT_SAVE,
  API_URL_PRODUCT_Add,
  API_URL_PRODUCT_ID,
  API_URL_PRODUCT_TYPE_LIST,
  API_URL_UPLOAD_SINGLE_FILE_URL,
  API_URL_PACKAGE_LIST,
  API_URL_PACKAGE_TYPE_LIST,
  API_URL_PACKAGE_DETAIL_ID,
  API_URL_PACKAGE_SAVE,
  API_URL_IFDEFINES_LIST
} from '@/api/manage'
import {ref, reactive, getCurrentInstance, onBeforeUnmount, nextTick} from 'vue'
import { message, Modal } from 'ant-design-vue'
import { Editor, Toolbar, getEditor, removeEditor } from '@wangeditor/editor-for-vue'
import { IToolbarConfig } from '@wangeditor/editor'
import axios from 'axios'
import '@wangeditor/editor/dist/css/style.css'
import storage from '@/utils/jeepayStorageWrapper'
import { array } from "snabbdom";
// 导入全局函数
const { $infoBox, $access, $hasAgentEnt } = getCurrentInstance()!.appContext.config.globalProperties
const saveRule = {
  name: [{ required: true, message: '请输入方案名称', trigger: 'blur' }],
  // packageState: [{ required: true, message: '请选择方案状态', trigger: 'blur' }],
  // productState:[{required: true,message: '请选择状态',  type: 'blur'}],
  // price: [{ required: true, message: '请输入方案金额' }],
  packageUrl: [{ required: true, message: '请填写方案文档地址', trigger: 'blur' }],
  ids: [{ required: true, message: '请选择选择产品', trigger: 'blur' }],
  desc: [{ required: true, message: '请填写方案描述', trigger: 'blur' }],
  packageSpecs: [{ required: true, message: '请输入方案类型', trigger: 'blur' }],
  typeName: [{ required: true, message: '请选择分类' }],
  packageSort: [{ required: true, message: '请输入排序' }],

  // productUrl: [{ required: true, message: '请填写产品文档地址', trigger: 'blur' }],
  packageLogoUrl: [{ required: true, message: '请上传方案LOGO', trigger: 'blur' }],
  // content: [{ required: true, message: '请填写产品内容', trigger: 'blur' }],
  charge: [{ required: true, message: '请填选择是否收费', trigger: 'blur' }],
  audit: [{ required: true, message: '请填选择需要审核', trigger: 'blur' }],
  certification: [{ required: true, message: '请填选择需要审核', trigger: 'blur' }],
}
const upload = ref()
const noticeViewer = ref() //查看详情
const plainOptions = [
  { label: '商户', value: 'MCH' },
  { label: '代理商', value: 'AGENT' }
]
const jeepayModelPayInterfaceListRef = ref()
const jeepayModelProgrammeListRef = ref()
const jeepayModelProductListRef = ref()
const infoFormModel = ref()
const infoTable = ref()
const dateRangePicker = ref()
// 定义一个编辑器 id ，要求：全局唯一且不变！！！
const editorId = 'wangeEditor-1' // 富文本编辑器
// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: { /* 菜单配置，下文解释 */ }
}
type InsertFnType = (url: string, alt: string, href: string) => void
editorConfig.MENU_CONF['uploadImage'] = {
  base64LimitSize: 10 * 1024, // 10kb以内的图片不上传
  // // 用户自定义上传图片
  customUpload(file, insertFn) {
    $getUploadFormParams(file, 'notice').then(res => {
      // 如果值为LOCAL_SINGLE_FILE_URL 则是本地存储
      if (res.formActionUrl == 'LOCAL_SINGLE_FILE_URL') {
        res.bizType = 'notice'
        res.formActionUrl = API_URL_UPLOAD_SINGLE_FILE_URL
      }
      //uploadRes没用处
      upLoadFile(res.formActionUrl, res.formParams, file, res.bizType, insertFn).then(uploadRes => {
        // 如果存在bizTye 则是本体存储 需要在 请求回来后显示图片
        if (res.bizType) return
        insertFn(res.ossFileUrl, file.name, res.ossFileUrl)
      })
    }).catch(err => {
      $infoBox.message.success('上传失败', err)
    })
  },

}


// 定义一个编辑器 id ，要求：全局唯一且不变！！！
// const editorId3 = 'wangeEditor-2' // 富文本编辑器
// 编辑器配置
const editorConfig3 = {
  placeholder: '请输入内容...',
  MENU_CONF: { /* 菜单配置，下文解释 */ }
}
type InsertFnType3 = (url: string, alt: string, href: string) => void
editorConfig3.MENU_CONF['uploadImage'] = {
  base64LimitSize: 10 * 1024, // 10kb以内的图片不上传
  // // 用户自定义上传图片
  customUpload(file, insertFn) {
    $getUploadFormParams(file, 'notice').then(res => {
      // 如果值为LOCAL_SINGLE_FILE_URL 则是本地存储
      if (res.formActionUrl == 'LOCAL_SINGLE_FILE_URL') {
        res.bizType = 'notice'
        res.formActionUrl = API_URL_UPLOAD_SINGLE_FILE_URL
      }
      //uploadRes没用处
      upLoadFile(res.formActionUrl, res.formParams, file, res.bizType, insertFn).then(uploadRes => {
        // 如果存在bizTye 则是本体存储 需要在 请求回来后显示图片
        if (res.bizType) return
        insertFn(res.ossFileUrl, file.name, res.ossFileUrl)
      })
    }).catch(err => {
      $infoBox.message.success('上传失败', err)
    })
  },

}

// 隐藏编辑器菜单中，一些菜单项
const toolbarConfig: Partial<IToolbarConfig> = {
  // 隐藏 全屏放大  上传视频  等
  excludeKeys: ['fullScreen', 'uploadVideo', 'insertVideo', 'deleteVideo',]
}
// eslint-disable-next-line no-unused-vars
const tableColumns = reactive([
  { key: 'name', title: '方案名称', dataIndex: 'name', align: 'center' },
  { key: 'typeName', title: '方案分类' },
  { key: 'packageState', title: '状态', dataIndex: 'packageState' },
  // { key: 'productDesc', title: '描述', dataIndex: 'productDesc',width:500 },
  { key: 'charge', title: '是否收费', dataIndex: 'charge' },
  { key: 'audit', title: '是否审核', dataIndex: 'audit' },
  { key: 'applyForCount', title: '申请数量', dataIndex: 'applyForCount' },
  { key: 'orderCount', title: '订购数量', dataIndex: 'orderCount' },
  { key: 'packageSort', title: '排序', dataIndex: 'packageSort' },
  { key: 'createdAt', dataIndex: 'createdAt', title: '创建日期' },
  { key: 'op', title: '操作', fixed: 'right', align: 'center' }
])

const vdata = reactive({
  title: '',
  productArrList: [] as any,
  IfDefinesList: [] as any,
  packageList: [] as any,
  packageTypeList: [] as any,
  fileProductTypeList: [] as any,
  filePackageTypeList: [] as any,
  productList: [] as any,
  searchData: {} as any,
  btnLoading: false,
  content: '',
  text: '',
  recordId: '',
  typeList: {} as any,
  noticeDate: { packageSort: 100 } as any,
  isAdd: false, //是否为新建方案
  avatarUrl: '',
  certificationDataSource: [{ key: 0, inputType: `file`, certificationUrl: '', certificationName: '' }],
  feeColumns: [
    {
      title: '版本名称',
      dataIndex: 'versionName',
      slots: { customRender: 'versionName' },
    },
    {
      title: '有效时间',
      dataIndex: 'validTime',
      slots: { customRender: 'validTime' },
    },
    {
      title: '售卖价格',
      dataIndex: 'sellingPrice',
      slots: { customRender: 'sellingPrice' },
    },
    {
      title: '划线价',
      dataIndex: 'lineationPrice',
      slots: { customRender: 'lineationPrice' },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      slots: { customRender: 'operation' },
      width: '15%',
    },
  ],
  plainOptions: [{ name: '接口型', lable: 0 }, { name: '服务型', lable: 1 }],
  feeDataSource: [{
    versionName: '',
    validTime: '',
    sellingPrice: '',
    lineationPrice: '',
    key: 0 as any,
  },],
  certificationColumns: [
    { title: '模版名称', dataIndex: 'certificationName', },
    { title: '填充类型', dataIndex: 'certificationUrl', width: '30%', ellipsis: true, },
    { title: '操作', dataIndex: 'operation', },
  ]
})

const packageIds = ref([])
let visible = ref(false)
// 重置表单验证规则
if (infoFormModel.value) {
  infoFormModel.value.resetFields()
}
// 请求table接口数据
function reqTableDataFunc(params) {
  return req.list(API_URL_PACKAGE_LIST, params)
}



const onAdd = () => {
  vdata.feeDataSource.push({
    versionName: '',
    validTime: '',
    sellingPrice: '',
    lineationPrice: '',
    key: vdata.feeDataSource[vdata.feeDataSource.length - 1].key + 1,
  })
}

const onDelete = (key) => {
  if (vdata.feeDataSource.length <= 1) {
    $infoBox.message.error('最少保留一项')
    return false
  }
  vdata.feeDataSource = vdata.feeDataSource.filter(item => item.key !== key)
}

const handleAdd = () => {
  vdata.certificationDataSource.push({ key: vdata.certificationDataSource[vdata.certificationDataSource.length - 1].key + 1, inputType: `file`, certificationUrl: ``, certificationName: '', })
}

const certificationOnDelete = (key) => {
  if (vdata.certificationDataSource.length <= 1) {
    $infoBox.message.error('最少保留一项')
    return false
  }
  vdata.certificationDataSource = vdata.certificationDataSource.filter(item => item.key !== key)
}


function  updateState (recordId, state) { // 【更新状态】

  const title = state === 1 ? '确认[上架]？' : '确认[下架]？'
  return $infoBox.confirmDangerPromise(title, '').then(() => {

    return req.updateById(API_URL_PRODUCT_SAVE, recordId, {packageId: recordId, packageState: state})
        .then(res => {
          $infoBox.message.success('修改成功')
          vdata.btnLoading = false
          visible.value = false
          queryhFunc()
        }).catch(res => {
          vdata.btnLoading = false
        })

    // return reqLoad.updateById(API_URL_PRODUCT_SAVE, vdata.recordId, { qrcState: state })
  })
}

function delFunc(articleId) {
  if (!articleId) {
    return message.error('请选择要删除的方案')
  }
  Modal.confirm({
    title: '确认删除方案吗？',
    okType: 'danger',
    onOk() {
      req.delById(API_URL_PRODUCT_SAVE, articleId).then(res => {
        infoTable.value.refTable(true)
        $infoBox.message.success('删除成功')
      })
    },
  })
}
function addNewNotice() {
  visible.value = true
  vdata.isAdd = true
  vdata.noticeDate = { packageSort: 100 }
  vdata.content = ''
  vdata.text = ''
}
function editFunc(record) {
  getEditSave()
  console.log(record, 'recordrecordrecord')
  vdata.recordId = record.packageId
  // vdata.content = record.packageContent
  // vdata.text = record.packageText
  // vdata.noticeDate = record
  // visible.value = true
  // vdata.isAdd = false

  req.list(API_URL_PACKAGE_DETAIL_ID, { packageId: record.packageId }).then(res => {
    vdata.content = res.packageContent
    // vdata.noticeDate.productIds
    vdata.feeDataSource = res.packageText
    vdata.certificationDataSource = res.specialCertificationText
    vdata.noticeDate = res
    packageIds.value = res.ids
    visible.value = true
    vdata.isAdd = false
  })
}
function changeFunc(value, selectedOptions) {
  console.log(value);

  vdata.noticeDate.typeName = value
  vdata.noticeDate.packageType = selectedOptions.key
}
//查看详情
function detailFunc(recordId) {
  noticeViewer.value.showDrawer(recordId)
}

function onClose() {
  visible.value = false
}
function queryhFunc() {
  vdata.btnLoading = true
  infoTable.value.refTable(true)
}
function confirm() {
  infoFormModel.value.validate().then(() => {
    const editor: any = getEditor(editorId)
    // const editor3: any = getEditor(editorId3)

    vdata.btnLoading = true // 打开按钮上的 loading
    vdata.noticeDate.packageContent = editor.getHtml() //富文本内容
    // vdata.noticeDate.packageText = editor3.getHtml() //富文本内容
    
    // vdata.noticeDate.packageIds = packageIds.value //富文本内容

    if (vdata.noticeDate.packageContent == "<p><br></p>") {
      vdata.btnLoading = false
      $infoBox.message.error('请填写方案内容')
      return false
    }

    // if (vdata.noticeDate.packageText == "<p><br></p>") {
    //   vdata.btnLoading = false
    //   $infoBox.message.error('请填写收费信息')
    //   return false
    // }
    if (vdata.noticeDate.productIds == undefined) {
      vdata.btnLoading = false
      $infoBox.message.error('请选择关联产品')
      return false;
    }
    if (vdata.noticeDate.packageIds == undefined) {
      vdata.btnLoading = false
      $infoBox.message.error('请选择关联方案')
      return false;
    }
    if (vdata.noticeDate.payInterfaceCodes == undefined) {
      vdata.btnLoading = false
      $infoBox.message.error('请选择关联通道')
      return false;
    }
    if (Array.isArray(vdata.noticeDate.productIds)) {
      vdata.noticeDate.productIds = vdata.noticeDate.productIds.join(',');
    }

    if (Array.isArray(vdata.noticeDate.packageIds)) {
      vdata.noticeDate.packageIds = vdata.noticeDate.packageIds.join(',');
    }
    if (Array.isArray(vdata.noticeDate.payInterfaceCodes)) {
      vdata.noticeDate.payInterfaceCodes = vdata.noticeDate.payInterfaceCodes.join(',');
    }


    if (vdata.noticeDate.charge === 1) {
      let feeDataSourceFlag = vdata.feeDataSource.every((item) => {
        if (item.versionName === '' || item.validTime === '' || item.sellingPrice === '' || item.lineationPrice === '') {
          return false
        } else {
          return true
        }
      })
      if (!feeDataSourceFlag) {
        $infoBox.message.error('请填写完整的销售规则')
        vdata.btnLoading = false
        return false
      } else {
        vdata.noticeDate.productText = vdata.feeDataSource
      }
    }

    if (vdata.noticeDate.certification === 1) {
      let certificationDataSourceFlag = vdata.certificationDataSource.every((item) => {
        console.log(item);
        if (item.certificationName === '' || item.certificationUrl === '') {
          return false
        } else {
          return true
        }
      })


      if (!certificationDataSourceFlag) {
        $infoBox.message.error('请填写完整的销售规则')
        vdata.btnLoading = false
        return false
      } else {
        vdata.noticeDate.specialCertificationText = vdata.certificationDataSource
      }
    }


    if (vdata.isAdd) {
      req.add(API_URL_PACKAGE_SAVE, vdata.noticeDate)
        .then(res => {
          $infoBox.message.success('添加成功')
          vdata.btnLoading = false
          visible.value = false
          queryhFunc()
        }).catch(res => { vdata.btnLoading = false })
    } else {
      req.add(API_URL_PACKAGE_SAVE, vdata.noticeDate)
        .then(res => {
          $infoBox.message.success('修改成功')
          vdata.btnLoading = false
          visible.value = false
          queryhFunc()
        }).catch(res => { vdata.btnLoading = false })
    }
  })

}
// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = getEditor(editorId)
  if (editor == null) return
  // 销毁，并移除 editor
  editor.destroy()
  removeEditor(editorId)

  // const editor3 = getEditor(editorId3)
  // if (editor3 == null) return
  // // 销毁，并移除 editor3
  // editor3.destroy()
  // removeEditor(editorId3)
})
//上传图片
const upLoadFile = (url, data, file, bizType, insertFn) => {
  let formData = new FormData()
  if (bizType) formData.append('bizType', bizType)
  formData.append('OSSAccessKeyId', data.OSSAccessKeyId)
  formData.append('key', data.key)
  formData.append('Signature', data.Signature)
  formData.append('policy', data.policy)
  formData.append('success_action_status', data.success_action_status)
  formData.append('file', file)
  return axios({
    url: url,
    method: 'POST',
    data: formData,
    headers: {
      iToken: storage.getToken(),
      'content-type': 'multipart/form-data'
    },
  }).then(({ data }) => {
    // 如果为本地存储 显示图片
    if (bizType) {
      insertFn(data.data)
    }
  })
}

function onReset() {
  //重置搜索内容
  dateRangePicker.value.returnSelectModel()
  vdata.searchData = { queryDateRange: '' }
}
getProductTypeList()
function getProductTypeList() {
  req.list(API_URL_PRODUCT_TYPE_LIST, { pageSize: -1 }).then(res => {
    vdata.typeList = res.records
    vdata.fileProductTypeList = res.records
  }).catch(res => {
  })
}

getPackageTypeList()
function getPackageTypeList() {
  req.list(API_URL_PACKAGE_TYPE_LIST, { pageSize: -1 }).then(res => {
    vdata.packageTypeList = res.records
    vdata.filePackageTypeList = res.records
  }).catch(res => {
  })
}
getPackageList()
//方案
function getPackageList() {
  req.list(API_URL_PACKAGE_LIST, { pageSize: -1 }).then(res => {
    vdata.packageList = res.records
  }).catch(res => {
  })
}
getProductList()
//产品
function getProductList() {
  req.list(API_URL_PRODUCT_LIST, { pageSize: -1 }).then(res => {
    vdata.productArrList = res.records
  }).catch(res => {
  })
}
getIfDefinesList()
function getIfDefinesList() {
  req.list(API_URL_IFDEFINES_LIST, '').then(res => {
    vdata.IfDefinesList = res
  }).catch(res => {
  })
}
function getEditSave() {
  vdata.fileProductTypeList = []
  vdata.fileProductTypeList = vdata.typeList
  let productArrList = vdata.productArrList;
  for (let index in vdata.fileProductTypeList) {
    vdata.fileProductTypeList[index]['children'] = [];
    for (let key in productArrList) {
      if (productArrList[key].productType == vdata.fileProductTypeList[index].typeId) {

        vdata.fileProductTypeList[index]['children'].push(productArrList[key]);
      }
    }
  }



  let filePackageTypeList = vdata.packageTypeList

  let packageList = vdata.packageList;
  for (let index3 in filePackageTypeList) {
    filePackageTypeList[index3]['children'] = [];
    for (let key2 in packageList) {
      if (packageList[key2].packageType == filePackageTypeList[index3].typeId) {
        filePackageTypeList[index3]['children'].push(packageList[key2]);
      }
    }
  }
  console.log(filePackageTypeList, 'filePackageTypeList')
  vdata.filePackageTypeList = filePackageTypeList

}

const JeepayModelProductListFlag =ref(false)
function showQrcSelectProductModel(title) {
  vdata.title = title
  JeepayModelProductListFlag.value=true
  nextTick(()=>{
    jeepayModelProductListRef.value.show()
  })
}
function selectQrcFinishProductFunc(e) { // 码牌选择完成事件
  JeepayModelProductListFlag.value=false
  if (!e || e.length <= 0) {
    vdata.noticeDate.productIdsName = ''
    vdata.noticeDate.productIds = []
    return $infoBox.message.error('请开启要绑定的产品！')
  }
  vdata.noticeDate.productIdsName = ''
  vdata.noticeDate.productIds = []

  e.forEach((item) => {
    vdata.noticeDate.productIdsName += item.productName + ','
    vdata.noticeDate.productIds.push(item.productId)
  })
  jeepayModelProductListRef.value.close()
}
const jeepayModelProgrammeListFlag = ref(false)


function showQrcSelectPackageModel(title) {
  vdata.title = title
  jeepayModelProgrammeListFlag.value = true
  nextTick(() => {
    jeepayModelProgrammeListRef.value.show()
  })
}
function selectQrcFinishPackageFunc(e) { // 码牌选择完成事件
  jeepayModelProgrammeListFlag.value = false

  if (!e || e.length <= 0) {
    vdata.noticeDate.packageName = ''
    vdata.noticeDate.packageIds = []
    return $infoBox.message.error('请开启要绑定的方案！')
  }
  vdata.noticeDate.packageName = ''
  vdata.noticeDate.packageIds = []
  e.forEach((item) => {
    vdata.noticeDate.packageName += item.name + ','
    vdata.noticeDate.packageIds.push(item.packageId)
  })
  jeepayModelProgrammeListRef.value.close()
}


function showQrcSelectPayInterfaceModel(title) {
  vdata.title = title
  JeepayModelPayInterfaceListFlag.value = true
  nextTick(() => {
    jeepayModelPayInterfaceListRef.value.show()
  })
}

const JeepayModelPayInterfaceListFlag = ref(false)

function selectQrcFinishPayInterfaceFunc(e) { // 码牌选择完成事件
  JeepayModelPayInterfaceListFlag.value = false
  if (!e || e.length <= 0) {
    vdata.noticeDate.payInterfaceName = ''
    vdata.noticeDate.payInterfaceCodes = []
    return $infoBox.message.error('请开启要绑定的通道！')
  }
  vdata.noticeDate.payInterfaceName = ''
  vdata.noticeDate.payInterfaceCodes = []
  e.forEach((item) => {
    vdata.noticeDate.payInterfaceName += item.ifName + ','
    vdata.noticeDate.payInterfaceCodes.push(item.ifCode)
  })
  jeepayModelPayInterfaceListRef.value.close()
}

</script>

<style scoped>
.collapse-div :deep(.ant-form-item-label label) {
  font-size: 12px;
  font-weight: bold;
}
</style>


