<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <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="secondName">
        <el-input
          v-model="queryParams.secondName"
          placeholder="套餐包别名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品编码" prop="secondName">
        <el-input
          v-model="queryParams.secondName"
          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="packageType">
        <el-select v-model="queryParams.packageType" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in packageTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="疾病类型" prop="diseaseType">
        <el-select v-model="queryParams.diseaseType" placeholder="请选择疾病类型" clearable size="small">
          <el-option
            v-for="dict in diseaseTypeOptions"
            :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 label="私域疗法类型" prop="privateType" >
        <el-select v-model="queryParams.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="solarTerm" >
        <el-select v-model="queryParams.solarTerm" placeholder="请选择">
          <el-option
            v-for="dict in solarTermOptions"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属小程序" prop="appName" >
        <el-select v-model="queryParams.appId" placeholder="请选择" clearable>
          <el-option
            v-for="dict in appMallOptions"
            :key="dict.appid"
            :label="dict.name + '(' + dict.appid + ')'"
            :value="dict.appid"
          />
        </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="multiple"
          @click="handleUpdateMore"
          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="['his:package:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
              <el-button
                type="info"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"

              >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="multiple"
          @click="bulkCopy"
          v-hasPermi="['his:package:bulkCopy']"
        >批量复制</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table height="600" 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" width="100px"/>
      <el-table-column label="套餐包名称" align="center" prop="packageName" />
      <el-table-column label="别名" align="center" prop="secondName" />
      <el-table-column label="排序" align="center" prop="sort" width="50px"/>
      <el-table-column label="状态" align="center" prop="status" width="65px">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="packageType" width="70px">
        <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" width="75px">
        <template slot-scope="scope">
          <dict-tag :options="orOptions" :value="scope.row.isShow"/>
        </template>
      </el-table-column>
      <el-table-column label="节气" align="center" prop="solarTerm" width="75px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.solarTerm">{{getSolarTermLabel(scope.row.solarTerm)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180px"/>
      <el-table-column label="更改时间" align="center" prop="updateTime" width="180px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180px">
        <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="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-item label="所属小程序" prop="appId">
          <el-select v-model="appId" placeholder="请选择所属小程序" clearable size="small" multiple>
            <el-option
              v-for="dict in appMallOptions"
              :key="dict.appid"
              :label="dict.name + '(' + dict.appid + ')'"
              :value="dict.appid"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="问答" prop="questionId" >
           <el-select v-model="form.questionId" placeholder="请选择问答">
              <el-option
                  v-for="dict in questionOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(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-dialog title="添加商品" :visible.sync="drugOpen" width="1000px" append-to-body>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="drugOpen=false">确 定</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>


        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
              <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                  <div class="el-upload__tip" slot="tip">
               <!--     <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据 -->
                  </div>
                  <span>仅允许导入xls、xlsx格式文件。</span>
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
                </div>
              </el-upload>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
              </div>
            </el-dialog>
    <el-dialog :title="title" :visible.sync="open1" width="580px" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules" label-width="80px">
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form1.status">
            <el-radio :label="item.dictValue" v-for="item in statusOptions" >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPackage,
  getPackage,
  delPackage,
  addPackage,
  updatePackage,
  exportPackage,
  importTemplate,
  modifyPackages,
  bulkCopy
} from "@/api/his/package";
import {getAllFollowTempName } from "@/api/his/followTemp";
import {getAllCateList} from "@/api/his/packageCate";
import {allIcd } from "@/api/his/icd";
// import {questionOptions } from "@/api/his/answer";
import packageDetails from '../../components/his/packageDetails.vue';
import productAttrValueSelect from "../../components/his/productAttrValueSelect.vue";
import { listStore } from "@/api/his/storeProduct";
import Editor from '@/components/Editor/wang';
import { getToken } from "@/utils/auth";
import Material from '@/components/Material'
import ImageUpload from '@/components/ImageUpload'
import { Loading } from 'element-ui';
import { getOptions } from '@/api/his/packageSolarTerm';
import {list as getAppMallOptions} from '@/api/course/coursePlaySourceConfig';
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 {
      appId:[],
      open1: false,
      form1:{},
      finalQuality:1,
      product:{
        open:false,
        title:"商品选择"
      },
      icdList:[],
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      baseUrl: process.env.VUE_APP_BASE_API,
      upload: {
              // 是否显示弹出层
              open: false,
              // 弹出层标题
              title: "",
              // 是否禁用上传
              isUploading: false,
              // 是否更新已经存在的用户数据
              updateSupport: 0,
              // 设置上传的请求头部
              headers: { Authorization: "Bearer " + getToken() },
              // 上传的地址
              url: process.env.VUE_APP_BASE_API + "/his/package/importData"
            },
      productTypeOptions: [],
      // questionOptions: [],
      storeId:null,
      storeOPtions:[],
      usageFrequencyUnitOptions:[{
          value: '每日一次',
          label: '每日一次'
        }, {
          value: '每日二次',
          label: '每日二次'
        }, {
          value: '每日三次',
          label: '每日三次'
        }, {
          value: '每日四次',
          label: '每日四次'
        }, {
          value: '每日五次',
          label: '每日五次'
        }],
      totalMoney:0.00,
      drugOpen:false,
      checkList: ['1'],
      drugList:[],
      show:{
              open:false,
            },
      productJson: [],
      describeJson:{usageMethod:"",forPeople:"",tabootPeople:"",use:""},
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 套餐包表格数据
      packageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      tempOptions: [],
      statusOptions: [],
      payTypeOptions: [],
      orOptions:[],
      packageTypeOptions: [],
      diseaseTypeOptions: [],
      privateTypeOptions: [],
      // 是否删除字典
      isDelOptions: [],
      packageSubTypeOptions:[],
      solarTermOptions: [],
      appMallOptions:[],
      photoArr:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        packageName: null,
        sort: null,
        productJson: null,
        status: null,
        isDel: null,
        solarTerm: 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;
    });
    getAllCateList().then(response => {
      this.diseaseTypeOptions = response.data.diseaseType;
      this.privateTypeOptions = response.data.privateType;
    });
    this.getTemp();
    this.getSolarTermOptions(),
    this.getAppMallOptions();
    listStore().then(response => {
      this.storeOPtions = response.rows;
    });
    // questionOptions().then(res => {
    //   this.questionOptions = res.rows;
    // })
  },
  methods: {
    getSolarTermLabel(solarTerm) {
      if (solarTerm) {
        return this.solarTermOptions.find(item => item.value === solarTerm)?.label || '-'
      }
      return '-'
    },
    getSolarTermOptions() {
      getOptions().then(response => {
        this.solarTermOptions = response.data;
      })
    },
    getAppMallOptions() {
      getAppMallOptions({pageNum:1,pageSize:100,isMall:1}).then(response => {
        this.appMallOptions = response.rows;
      })
    },
    handleUpdateMore(row){
      this.reset1();
      this.title = "批量修改套餐状态";
      const packageIds = row.packageId || this.ids;
      this.form1.packageIds=packageIds;
      this.open1 = true;
    },
    // 取消按钮
    cancel1() {
      this.open1 = false;
      this.reset1();
    },
    // 表单重置
    reset1() {
      this.form1 = {
        status:"1",
        packageIds:[],
      };
      this.resetForm("form1");
    },
    /** 提交按钮 */
    submitForm1() {

      if (this.form1.status == null) {
        this.msgError("请选择套餐状态");
        return;
      }
      this.$refs["form1"].validate(valid => {
        if (valid) {
          if (this.form1.packageIds != null) {
            modifyPackages(this.form1).then(response => {
              if (response.code === 200) {
                this.msgSuccess("操作成功");
                this.open1 = false;
                this.getList();
              }
            });
          }
        }
      });
    },
     updateText(text){
          this.form.desc=text
        },
    addDrug(row){
      this.drugList=row.row.drug
      this.drugOpen=true;
    },
    updateText2(text){
         this.describeJson.usageMethod=text
       },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    icdMethod(query){
      if (query !== '') {
        allIcd(query).then(response => {
        this.icdList = response.data;
      });
      }
    },
        /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
        // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    getTemp(){
      getAllFollowTempName().then(response => {
        this.tempOptions = response.rows;
      });
      },
        // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handledetails(row){
            this.show.open=true;
            setTimeout(() => {
                 this.$refs.Details.getDetails(row.packageId);
            }, 1);
        },

    /** 查询套餐包列表 */
    getList() {
      this.loading = true;
      listPackage(this.queryParams).then(response => {
        this.packageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    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;
      }
    },
    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'
              });
    },
    // 取消按钮
    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();
      this.storeId=null,
      this.drugList=null,
      this.describeJson ={usageMethod:"",forPeople:"",tabootPeople:"",use:""};
      const packageId = row.packageId || this.ids


      getPackage(packageId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改套餐包";
        if(this.form.images!=null){
          this.photoArr=this.form.images.split(",");
        }
        if(this.form.productJson!=null&&this.form.productJson!=""){
          this.drugList=JSON.parse(this.form.productJson)
        }else{
          this.drugList=[];
        }
        if(this.form.icdCode!=null){
           this.form.icdCode=this.form.icdCode.split(",")
        }


        if(this.form.payType!=null ){
          this.checkList=this.form.payType.split(',')
        }
        if(this.form.packageType!=null ){
          this.form.packageType=JSON.stringify(this.form.packageType)
        }
        if(this.form.recipeType!=null ){
          this.form.recipeType=JSON.stringify(this.form.recipeType)
        }
        if(this.form.packageSubType!=null ){
          this.form.packageSubType=JSON.stringify(this.form.packageSubType)
        }
        if(this.form.isShow!=null ){
          this.form.isShow=JSON.stringify(this.form.isShow)
        }
        if(this.form.describeJson!=null ){
          this.describeJson=JSON.parse(this.form.describeJson)
        }
        if(this.form.productType!=null ){
          this.form.productType=JSON.stringify(this.form.productType)
        }
        if(this.form.followNum!=null ){
          this.form.followNum=JSON.stringify(this.form.followNum)
        }
        this.appId=this.form.appIds ? this.form.appIds.split(',') : [];
        setTimeout(() => {
                  if(this.form.desc==null){
                    this.$refs.myeditor.setText("");
                  }
                  else{
                    this.$refs.myeditor.setText(this.form.desc);
                  }
                }, 1);
        setTimeout(() => {
                  if(this.describeJson.usageMethod==null){
                    this.$refs.myeditor2.setText("");
                  }
                  else{
                    this.$refs.myeditor2.setText(this.describeJson.usageMethod);
                  }
                }, 1);
      });
    },
    /** 提交按钮 */
    submitForm() {

      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);
          const params = {
            ...this.form,
            appIds: this.appId.join(',') // 数组转字符串
          };
          if (params.packageId != null) {
            updatePackage(params).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPackage(params).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
     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);
        };
      });
    },
    /** 删除按钮操作 */
    bulkCopy(row) {
      const packageIds = row.packageId || this.ids;
      this.$confirm('是否确认复制套餐包编号为"' + packageIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return bulkCopy(packageIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("批量复制成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    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>
