<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="套餐包名称" prop="packageName">
        <el-input v-model="queryParams.packageName" placeholder="请输入套餐包名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="子类型" prop="packageSubType">
        <el-select v-model="queryParams.packageSubType" placeholder="请选择" clearable size="small">
          <el-option v-for="dict in packageSubTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['his:package:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['his:package:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['his:package:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading"
          @click="handleExport" v-hasPermi="['store:package:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="packageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="packageId" />
      <el-table-column label="套餐包名称" align="center" prop="packageName" />
      <el-table-column label="排序号" align="center" prop="sort" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="packageType">
        <template slot-scope="scope">
          <dict-tag :options="packageTypeOptions" :value="scope.row.packageType" />
        </template>
      </el-table-column>
      <el-table-column label="子类型" align="center" prop="packageSubType">
        <template slot-scope="scope">
          <dict-tag :options="packageSubTypeOptions" :value="scope.row.packageSubType" />
        </template>
      </el-table-column>
      <el-table-column label="是否展示" align="center" prop="isShow">
        <template slot-scope="scope">
          <dict-tag :options="orOptions" :value="scope.row.isShow" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="更改时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <!--     <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:package:edit']"
          >修改</el-button> -->
          <el-button size="mini" type="text" @click="handledetails(scope.row)">详情
          </el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:package:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改套餐包对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="套餐包名称" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入套餐包名称" />
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
           <el-input-number v-model="form.sort"  :min="0" label="排序号"></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="价格配置" prop="priceJson">


                 <el-table :data="priceJson"    :cell-style="{ textAlign: 'center' }"		 :header-cell-style="{textAlign: 'center'}"   >
                   <el-table-column label="子套餐标题" prop="title" width="150px">
                     <template slot-scope="scope">
                       <el-input v-model="scope.row.title" ></el-input>
                     </template>
                   </el-table-column>
                   <el-table-column label="签约时长/日" prop="duration" width="150px">
                     <template slot-scope="scope">
                       <el-input-number v-model="scope.row.duration" controls-position="right" :min="0" size="small"></el-input-number>

                     </template>
                   </el-table-column>
                   <el-table-column label="价格/元" prop="price" width="150px">
                     <template slot-scope="scope">
                        <el-input-number v-model="scope.row.price" controls-position="right"  :min="0" size="small"></el-input-number>

                      </template>
                   </el-table-column>
                   <el-table-column label="状态"  prop="status">
                     <template slot-scope="scope">
                       <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949" ></el-switch>
                     </template>
                   </el-table-column>
                   <el-table-column label="操作">
                     <template slot-scope="scope">
                        <el-button @click="deleteRow(scope.$index)"   size="mini" type="text" v-if="priceJson.length>1">删除</el-button>
                         <el-button @click="addRow" size="mini" type="text" >新增</el-button>
                     </template>
                   </el-table-column>
                 </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="套餐包名称" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入套餐包名称" />
        </el-form-item>
        <el-form-item label="别名" prop="secondName">
          <el-input v-model="form.secondName" placeholder="请输入套餐包别名" />
        </el-form-item>
        <el-form-item label="封面图" prop="imgUrl">
          <el-upload
            v-model="form.imgUrl"
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar" width="300px">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播图" prop="images">
          <Material v-model="photoArr" type="image" :num="10" :width="150" :height="150" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="form.tags" placeholder="请输入标签" />
        </el-form-item>
        <el-form-item label="套餐包类型" prop="packageType">
          <el-radio-group v-model="form.packageType">
            <el-radio :label="item.dictValue" v-for="item in packageTypeOptions">{{ item.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="套餐包子类型" prop="packageSubType">
          <el-radio-group v-model="form.packageSubType">
            <el-tooltip content="咨询包不能推ERP" placement="top" :open-delay="100" v-if="form.packageType == 1">
              <el-radio label="1">咨询包</el-radio>
            </el-tooltip>
            <el-radio label="2" v-if="form.packageType == 1">治疗包</el-radio>
            <el-radio label="3" v-if="form.packageType == 2">产品包</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="药品类型" prop="productType" v-if="form.packageSubType != 1">
          <el-radio-group v-model="form.productType">
            <el-radio :label="item.dictValue" v-for="item in productTypeOptions">{{ item.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="药品制作类型" prop="recipeType" v-if="form.productType == 2 && form.packageSubType != 1">
          <el-radio v-model="form.recipeType" label="0">颗粒剂</el-radio>
          <el-radio v-model="form.recipeType" label="1">膏方</el-radio>
          <el-radio v-model="form.recipeType" label="2">饮片</el-radio>
        </el-form-item>

        <el-form-item label="剂数" prop="counts" v-if="form.productType == 2 && form.packageSubType != 1">
          <el-input-number v-model="form.counts" :min="1" label="剂数"></el-input-number>
        </el-form-item>
        <el-form-item label="一日几次" prop="usageFrequencyUnit" v-if="form.productType == 2 && form.packageSubType != 1">
          <el-select v-model="form.usageFrequencyUnit" placeholder="请选择">
            <el-option v-for="item in usageFrequencyUnitOptions" :key="item.value" :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用药数量" prop="tags">
          <el-input v-model="form.usagePerUseCount" placeholder="请输入用药数量" />
        </el-form-item>
        <el-form-item label="是否展示" prop="isShow">
          <el-radio-group v-model="form.isShow">
            <el-radio :label="item.dictValue" v-for="item in orOptions">{{ item.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="疾病类型" prop="diseaseType" v-if="form.isShow == 1">
          <el-select v-model="form.diseaseType" placeholder="请选择疾病类型">
            <el-option v-for="dict in diseaseTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)" />
          </el-select>
        </el-form-item>
        <el-form-item label="私域疗法类型" prop="privateType" v-if="form.isShow == 0">
          <el-select v-model="form.privateType" placeholder="请选择私域疗法类型">
            <el-option v-for="dict in privateTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)" />
          </el-select>
        </el-form-item>
        <el-form-item label="药品配置" prop="productJson">
          <el-select v-model="form.storeId" placeholder="请选择店铺" clearable size="small" filterable @change="changeStore">
            <el-option v-for="dict in storeOPtions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
          <div style="float: right;"><el-button plain type="primary" icon="el-icon-plus"
              @click="handleAddProduct">添加商品</el-button></div>
          <el-table border width="100%" style="margin-top:5px;" :data="drugList">
            <el-table-column label="商品图片" align="center" width="100">
              <template slot-scope="scope">
                <el-popover placement="right" title="" trigger="hover">
                  <img slot="reference" :src="scope.row.image" width="50">
                  <img :src="scope.row.image" style="max-width: 50px;">
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" show-overflow-tooltip align="center" prop="productName" />
            <el-table-column label="数量" align="center" prop="count" width="150px">
              <template slot-scope="scope">
                <div>
                  <el-input-number v-model="scope.row.count" @change="handleProductCountChange(scope.row)" size="small"
                    :min="1"></el-input-number>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="服用方法" align="center" prop="usageMethod" width="150px">
              <template slot-scope="scope">
                <div>
                  <el-input size="mini" v-model="scope.row.usageMethod"></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="一日几次" align="center" prop="usageFrequencyUnit" width="150px">
              <template slot-scope="scope">
                <div>
                  <el-input-number v-model="scope.row.usageFrequencyUnit" size="mini" :min="0"></el-input-number>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="用药数量" align="center" prop="usagePerUseCount">
              <template slot-scope="scope">
                <div>
                  <el-input size="mini" v-model="scope.row.usagePerUseCount"></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="规格" align="center" prop="prescribeSpec" />
            <el-table-column label="商品编号" align="center" prop="barCode" />
            <el-table-column label="商品规格" align="center" prop="sku" />
            <el-table-column label="店铺名称" align="center" prop="storeName" />
            <el-table-column label="成本价" align="center" prop="costPrice">
              <template slot-scope="scope">
                <div v-if="scope.row.costPrice != null">
                  {{ scope.row.costPrice.toFixed(2) }}
                </div>
              </template>
            </el-table-column>

            <el-table-column label="售价" align="center" prop="price">
              <template slot-scope="scope">
                <div v-if="scope.row.price != null">
                  {{ scope.row.price.toFixed(2) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="小计" align="center" prop="money">
              <template slot-scope="scope">
                <div v-if="scope.row.money != null">
                  {{ scope.row.money.toFixed(2) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100px" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete"
                  @click="handleProductDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row>
          </el-row>
        </el-form-item>
        <el-row>
          <el-col :span="12"></el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"></el-col>
          <el-col :span="12"></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="套餐价" prop="totalPrice">
              <el-input-number v-model="form.totalPrice" :min="0" label="套餐价"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总价 元/天" prop="price">
              <el-input-number v-model="form.price" :min="0" label="总价"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="医生服务时长" prop="duration">
              <el-input-number v-model="form.duration" :min="0" label="医生服务时长"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用药周期" prop="cycle">
              <el-input-number v-model="form.cycle" :min="0" label="用药周期"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="限购数量" prop="num">
              <el-input-number v-model="form.num" :min="0" label="限购数量"></el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="排序号" prop="sort">
              <el-input-number v-model="form.sort" :min="0" label="排序号"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="销量" prop="sales">
              <el-input-number v-model="form.sales" :min="0" label="销量"></el-input-number>
            </el-form-item>
          </el-col>

        </el-row>
        <el-form-item label="支付类型" prop="payType">
          <el-checkbox-group v-model="checkList">
            <el-checkbox label="1">全款支付</el-checkbox>
            <el-checkbox label="2">物流代收</el-checkbox>
            <el-checkbox label="3">货到付款</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="套餐详情" prop="desc">
          <Editor ref="myeditor" @on-text-change="updateText" />
        </el-form-item>
        <el-form-item label="服用方法" prop="usageMethod">
          <Editor ref="myeditor2" @on-text-change="updateText2" />
        </el-form-item>
        <el-form-item label="疗程" prop="use">
          <el-input type="textarea" :rows="4" v-model="describeJson.use" placeholder="请输入疗程" maxlength="2000" />
        </el-form-item>
        <el-form-item label="适用人群" prop="forPeople">
          <el-input type="textarea" :rows="4" v-model="describeJson.forPeople" placeholder="请输入适用人群" maxlength="2000" />
        </el-form-item>
        <el-form-item label="禁忌人群" prop="tabooPeople">
          <el-input type="textarea" :rows="4" v-model="describeJson.tabooPeople" placeholder="请输入禁忌人群"
            maxlength="2000" />
        </el-form-item>
        <el-form-item label="功能主治" prop="indication">
          <el-input type="textarea" :rows="4" v-model="form.indication" placeholder="请输入功能主治" maxlength="2000" />
        </el-form-item>
        <el-form-item label="方解" prop="explain">
          <el-input type="textarea" :rows="4" v-model="form.explain" placeholder="请输入方解" maxlength="2000" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" :rows="4" v-model="form.description" placeholder="请输描述" maxlength="100" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue"
              :label="parseInt(dict.dictValue)">{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="医嘱" prop="doctorRemark">
          <el-input type="textarea" :rows="3" v-model="form.doctorRemark" placeholder="请输入医嘱" />
        </el-form-item>
        <el-form-item label="icd编码" prop="icdCode">
          <el-select v-model="form.icdCode" remote filterable reserve-keyword placeholder="icd编码" multiple
            :remote-method="icdMethod">
            <el-option style="width: 300px;" v-for="dict in icdList" :key="dict.icdCode" :label="dict.icdCode"
              :value="dict.icdCode">
              <span style="float: left">{{ dict.icdCode }}</span>
              <span style="float: left">{{ dict.icdAddCode }}</span>
              <span style="margin-left: 30px">{{ dict.icdName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="节气" prop="solarTerm">
          <el-select v-model="form.solarTerm" placeholder="请选择节气" clearable size="small">
            <el-option v-for="dict in solarTermOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="随访模板" prop="followTempId">
          <el-select v-model="form.followTempId" placeholder="请选择模板" clearable size="small">
            <el-option v-for="dict in tempOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer :with-header="false" size="75%" :title="show.title" :visible.sync="show.open">
      <packageDetails ref="Details" />
    </el-drawer>
    <el-dialog :title="product.title" v-if="product.open"  :visible.sync="product.open" width="1000px" append-to-body>
      <product-attr-value-select  ref="Details"  @selectProduct="selectProduct" />
    </el-dialog>
  </div>
</template>

<script>
import { listPackage, getPackage, delPackage, addPackage, updatePackage, exportPackage } from "@/api/store/package";
import { getAllFollowTempName } from "@/api/store/followTemp";
import packageDetails from '../components/packageDetails.vue';
import productAttrValueSelect from "../components/productAttrValueSelect.vue";
import { allIcd } from "@/api/store/icd";
import Editor from '@/components/Editor/wang';
import Material from '@/components/Material';
import { listStore } from "@/api/store/storeProduct";
import { getAllCateList } from "@/api/store/packageCate";
import { Loading } from 'element-ui';
export default {
  name: "Package",
  components: { packageDetails, Editor, productAttrValueSelect, Material },
  watch: {
    imageArr: function (val) {
      this.form.imgUrl = val.join(',')
    },
    photoArr: function (val) {
      this.form.images = val.join(',')
    }
  },
  data() {
    return {
      product: {
        open: false,
        title: "商品选择"
      },
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/uploadOSS",
      photoArr: [],
      productTypeOptions: [],
      storeId: null,
      storeOPtions: [],
      usageFrequencyUnitOptions: [{
        value: '每日一次',
        label: '每日一次'
      }, {
        value: '每日二次',
        label: '每日二次'
      }, {
        value: '每日三次',
        label: '每日三次'
      }, {
        value: '每日四次',
        label: '每日四次'
      }, {
        value: '每日五次',
        label: '每日五次'
      }],
      totalMoney: 0.00,
      drugOpen: false,
      checkList: ['1'],
      drugList: [],
      productJson: [],
      describeJson: { usageMethod: "", forPeople: "", tabootPeople: "", use: "" },
      icdList: [],
      show: {
        open: false,
      },
      priceJson: [
        { title: "套餐1", duration: "0", price: "0", status: true },
      ],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 套餐包表格数据
      packageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      tempOptions: [],
      statusOptions: [],
      payTypeOptions: [],
      orOptions: [],
      packageTypeOptions: [],
      diseaseTypeOptions: [],
      packageSubTypeOptions: [],
      solarTermOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        packageName: null,
        sort: null,
        priceJson: null,
        status: null,
        isDel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        packageName: [
          { required: true, message: '套餐包名称不能为空', trigger: 'blur' }
        ],
        sort: [
          { type: 'number', message: '排序号必须为数字类型', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        packageType: [
          { required: true, message: '请选择套餐包类型', trigger: 'change' }
        ],
        isShow: [
          { required: true, message: '请选择是否展示', trigger: 'change' }
        ],
        packageSubType: [
          { required: true, message: '请选择是子类型', trigger: 'change' }
        ],
        diseaseType: [
          { required: true, message: '请选择是疾病类型', trigger: 'change' }
        ],
        imgUrl: [
          { required: true, message: '请添加封面图', trigger: 'change' }
        ],
        productType: [
          { required: true, message: '请选择药品类型', trigger: 'change' }
        ],
        recipeType: [
          { required: true, message: '请选择药品制作类型', trigger: 'change' }
        ],
        counts: [
          { required: true, message: '请选择剂数', trigger: 'change' }
        ],
        usageFrequencyUnit: [
          { required: true, message: '请选择一日几次', trigger: 'change' }
        ],
        privateType: [
          { required: true, message: '请选择私域类别', trigger: 'change' }
        ],
        followTempId: [
          { required: true, message: '请选择随访模板', trigger: 'change' }
        ],

      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_company_or").then(response => {
      this.isDelOptions = response.data;
      this.orOptions = response.data;
    });
    this.getDicts("sys_package_pay_type").then(response => {
      this.payTypeOptions = response.data;
    });
    this.getDicts("sys_product_type").then(response => {
      this.productTypeOptions = response.data;
    });
    this.getDicts("sys_package_type").then(response => {
      this.packageTypeOptions = response.data;
    });
    this.getDicts("sys_package_sub_type").then(response => {
      this.packageSubTypeOptions = response.data;
    });
    // this.getDicts("sys_prescribe_disease_type").then(response => {
    //   this.diseaseTypeOptions = response.data;
    // });
    getAllCateList().then(response => {
      this.diseaseTypeOptions = response.data.diseaseType;
      this.privateTypeOptions = response.data.privateType;
    });
    this.getTemp();
    listStore().then(response => {
      this.storeOPtions = response.rows;
    });
  },
  methods: {
    selectProduct(row){
      console.log(row)
      for(var i=0;i<this.drugList.length;i++){
        if(this.drugList[i].id==row.id){
          return;
        }
      }
      row.count=1;
      row.money=row.count*row.price;
      row.usageMethod="口服";
      row.usageFrequencyUnit=1;
      this.drugList.push(row);
      this.compute();
       this.$message({
                message: '添加成功',
                type: 'success'
              });
    },
    getTemp() {
      getAllFollowTempName().then(response => {
        this.tempOptions = response.rows;
      });
    },
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.form.imgUrl = res.url;
        // self.$forceUpdate()
      }
      else {
        this.msgError(res.msg);
      }
    },
    beforeAvatarUpload(file) {
        return new Promise((resolve, reject) => {
          if (file.size / 1024 / 1024 > 3) {
            this.$message.error('上传的图片不能超过3MB');
            reject();
            return;
          }
          if (file.size / 1024 > 500) {
            const loadingInstance = Loading.service({ text: '图片内存过大正在压缩图片...' });
            // 文件大于1MB时进行压缩
            this.compressImage(file).then((compressedFile) => {
              loadingInstance.close();
              if (compressedFile.size / 1024 > 500) {
                this.$message.error('图片压缩后仍大于500KB');
                reject();
              } else {
                // this.$message.success(`图片压缩成功，最终质量为: ${this.finalQuality.toFixed(2)}`);
                console.log(`图片压缩成功，最终质量为: ${this.finalQuality.toFixed(2)}`);
                console.log(`最终内存大小为: ${(compressedFile.size/1024).toFixed(2)}KB`);
                resolve(compressedFile);
              }
            }).catch((err) => {
              loadingInstance.close();
              console.error(err);
              reject();
            });
          } else {
            resolve(file);
          }
        });
      },
      compressImage(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (event) => {
          const img = new Image();
          img.src = event.target.result;
          img.onload = () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const width = img.width;
            const height = img.height;
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0, width, height);

            let quality = 1; // 初始压缩质量
            let dataURL = canvas.toDataURL('image/jpeg', quality);

            // 逐步压缩，直到图片大小小于500KB并且压缩质量不再降低
            while (dataURL.length / 1024 > 500 && quality > 0.1) {
              quality -= 0.01;
              dataURL = canvas.toDataURL('image/jpeg', quality);
            }
            this.finalQuality = quality; // 存储最终的压缩质量

            if (dataURL.length / 1024 > 500) {
              reject(new Error('压缩后图片仍然大于500KB'));
              return;
            }

            const arr = dataURL.split(',');
            const mime = arr[0].match(/:(.*?);/)[1];
            const bstr = atob(arr[1]);
            let n = bstr.length;
            const u8arr = new Uint8Array(n);
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n);
            }
            const compressedFile = new Blob([u8arr], { type: mime });
            compressedFile.name = file.name;
            resolve(compressedFile);
          };
          img.onerror = (error) => {
            reject(error);
          };
        };
        reader.onerror = (error) => {
          reject(error);
        };
      });
    },
    changeStore() {
      this.drugList = [];
    },
    handleProductCountChange(row){
      row.money=row.count*row.price;
      this.$forceUpdate();
      this.compute();
    },
    handleProductDelete(row){
       this.drugList.splice(this.drugList.findIndex(item => item.id === row.id), 1)
       this.compute();
    },
    compute(){
      this.totalMoney=0;
      var that=this;
      this.drugList.forEach (function (value) {
          that.totalMoney += value.money;
      });
      that.totalMoney=that.totalMoney.toFixed(2);
    },
    handleAddProduct() {
      if (this.form.storeId == null || this.form.storeId == "") {
        return this.$message({
          message: '请先选择店铺',
          type: 'warning'
        });
      } else {
        setTimeout(() => {
          this.$refs.Details.getDetails(this.form.storeId);
        }, 1);
        this.product.open = true;
      }
    },
    updateText(text) {
      this.form.desc = text
    },
    updateText2(text) {
      this.describeJson.usageMethod = text
    },
    icdMethod(query) {
      if (query !== '') {
        allIcd(query).then(response => {
          this.icdList = response.data;
        });
      }
    },
    handledetails(row) {
      this.show.open = true;
      setTimeout(() => {
        this.$refs.Details.getDetails(row.packageId);
      }, 1);
    },
    addRow() {
      this.priceJson.push({ title: "标题", duration: 0, price: 0, status: false });
    },
    deleteRow(index) {
      this.priceJson.splice(index, 1);
    },
    // saveData(row) {
    //   // 在这里可以进行数据保存操作，比如将数据提交到后端进行保存
    //   console.log("保存数据", row);
    // },
    /** 查询套餐包列表 */
    getList() {
      this.loading = true;
      listPackage(this.queryParams).then(response => {
        this.packageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        packageId: null,
        packageName: null,
        sort: null,
        productJson: null,
        status: 0,
        createTime: null,
        updateTime: null,
        isDel: null,
        payType: ["1"],
        isShow: "1",
        packageType: "1",
        num: null,
        price: null,
        sales: null,
        diseaseType: null,
        tags: null,
        packageSubType: "1",
        describeJson: null,
        productType: null,
        totalPrice: null,
        inquiryPrice: null,
        productPrice: null,
        cycle: null,
        duration: null,
        imgUrl: null,
        images: null,
        storeId: null,
        recipeType: null,
        counts: null,
        followNum: null,
        secondName: null,
      };
      this.photoArr = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.packageId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加套餐包";
      this.storeId = null,
        this.drugList = null,
        this.describeJson = { usageMethod: "", forPeople: "", tabootPeople: "", use: "" },
        setTimeout(() => {
          this.$refs.myeditor.setText("");
        }, 500);
      setTimeout(() => {
        this.$refs.myeditor2.setText("");
      }, 500);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const packageId = row.packageId || this.ids
      getPackage(packageId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改套餐包";
        this.priceJson = JSON.parse(this.form.priceJson)
      });
    },
    /** 提交按钮 */
    submitForm() {
      // this.$refs["form"].validate(valid => {
      //   if (valid) {
      //     for (var i = 0; i < this.priceJson.length; i++) {
      //       if (!this.priceJson[i].title) {
      //         this.$message("子标题不能为空")
      //         return;
      //       }
      //     }
      //     this.form.priceJson = JSON.stringify(this.priceJson)
      //     if (this.form.packageId != null) {
      //       updatePackage(this.form).then(response => {
      //         this.msgSuccess("修改成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       addPackage(this.form).then(response => {
      //         this.msgSuccess("新增成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     }
      //   }
      // });
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.icdCode!=null&&this.form.icdCode!=''){
            this.form.icdCode=(this.form.icdCode).toString();
          }else{
            this.form.icdCode=null;
          }
          this.form.payType=(this.checkList).toString()
          if(this.drugList!=null){
            this.form.productJson=JSON.stringify(this.drugList)
          }
          this.form.describeJson = JSON.stringify(this.describeJson);
          if (this.form.packageId != null) {
            updatePackage(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPackage(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const packageIds = row.packageId || this.ids;
      this.$confirm('是否确认删除套餐包编号为"' + packageIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delPackage(packageIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有套餐包数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportPackage(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => { });
    }
  }
};
</script>

<style>
.icon-button {
  border-radius: 0;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px !important;
  text-align: center;
}
</style>
