1
wwl
2025-03-13 319cf42af7648e99693f6eabfec4f842a40ed340
src/views/system/package/index.vue
@@ -103,10 +103,6 @@
      ></right-toolbar>
    </el-row>
    <!--
    element-loading-background="rgba(0, 0, 0, 0.1)"
    element-loading-spinner="el-icon-loading"
        element-loading-text="正在加载中..." -->
    <template>
      <el-table
        v-loading="loading"
@@ -129,7 +125,6 @@
          prop="newID"
          fixed
        />
        <!-- <el-table-column label="编号" align="center" prop="pacId" /> -->
        <el-table-column
          label="体检类别"
          width="100px"
@@ -166,7 +161,7 @@
          fixed
        ></el-table-column>
        <el-table-column
          label="优惠价"
          label="现价"
          width="80px"
          align="center"
          prop="newPrice"
@@ -180,13 +175,6 @@
          width="1200px"
        >
        </el-table-column>
        <!-- <el-table-column
          label="项目明细"
          align="center"
          prop="allSonName"
          :show-overflow-tooltip="true"
        >
        </el-table-column>-->
        <el-table-column
          label="套餐描述"
          align="center"
@@ -197,18 +185,6 @@
            <div class="showInline">{{ scope.row.pacRemark }}</div>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="图片"
          align="center"
          prop="pacPhone"
          width="100"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <image-preview :src="scope.row.pacPhone" :width="50" :height="50" />
          </template>
        </el-table-column> -->
        <el-table-column
          label="关键字"
          width="110px"
@@ -228,13 +204,6 @@
            />
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="详细介绍"
          :show-overflow-tooltip="true"
          width="100px"
          align="center"
          prop="detail"
        ></el-table-column> -->
        <el-table-column
          label="排序"
          width="50px"
@@ -247,12 +216,6 @@
          align="center"
          prop="retailPrice"
        ></el-table-column>
        <!-- <el-table-column
          label="原价"
          width="90px"
          align="center"
          prop="counterPrice"
        ></el-table-column> -->
        <el-table-column
          label="已售数量"
          width="90px"
@@ -299,8 +262,6 @@
              v-hasPermi="['system:package:remove']"
              title="删除"
            ></el-button>
            <!-- <el-button size="mini" type="text" icon="el-icon-circle-check" @click="handleSeach(scope.row)"
              v-hasPermi="['system:package:Seach']" title="套餐详情"></el-button> -->
          </template>
        </el-table-column>
      </el-table>
@@ -333,8 +294,6 @@
        label-width="100px"
        :inline="true"
      >
        <!-- <div class="dialo">
        <div class="dialo1"> -->
        <el-form-item label="套餐名称" prop="pacName">
          <span
            slot="label"
@@ -350,10 +309,6 @@
          />
        </el-form-item>
        <el-form-item label="套餐状态" prop="pacStatus">
          <!-- <el-radio-group v-model="form.pacStatus">
              <el-radio :label="0">启用</el-radio>
              <el-radio :label="1">停用</el-radio>
            </el-radio-group> -->
          <el-select
            v-model="form.pacStatus"
            placeholder="请选择状态"
@@ -369,24 +324,6 @@
            ></el-option>
          </el-select>
        </el-form-item>
        <!--  <el-form-item label="套餐类目" prop="categoryId">
          <el-select
            v-model="form.categoryId"
            placeholder="请选择套餐类目"
            style="width: 150px"
            @change="shangpin"
            filterable
            clearable
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="体检类别" prop="tjCategory">
          <el-select
            v-model="form.tjCategory"
@@ -403,12 +340,7 @@
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否上架" prop="isOnSale">
          <!-- <el-radio-group v-model="form.pacStatus">
              <el-radio :label="0">启用</el-radio>
              <el-radio :label="1">停用</el-radio>
            </el-radio-group> -->
          <el-select
            v-model="form.isOnSale"
            placeholder="请选择是否上架"
@@ -424,7 +356,6 @@
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input
            v-model="form.sort"
@@ -458,13 +389,17 @@
            @change="numberChange"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="优惠价">
        <el-form-item label="现价1">
          <el-input
            ref="inputName"
            v-model="form.xianprice"
            placeholder="优惠价"
            placeholder="请输入现价"
            clearable
            style="width: 140px"
            type="number"
            :min="0"
            @change="handleXianPriceChange"
            @input="handleXianPriceInput"
          />
        </el-form-item>
        <el-form-item label="关键字" prop="keywords">
@@ -498,11 +433,6 @@
              ></el-input>
            </el-form-item>
            <el-form-item label="详细介绍" prop="detail">
              <!-- <el-input
            v-model="form.detail"
            placeholder="请输入详细介绍"
            style="width: 200px"
          /> -->
              <editor
                v-model="form.detail"
                :min-height="192"
@@ -510,47 +440,16 @@
              />
            </el-form-item>
          </div>
          <!-- </div> -->
          <div class="dialo2">
            <el-form-item label="图片">
              <image-upload v-model="form.pacPhone" />
            </el-form-item>
          </div>
          <!-- </div> -->
        </div>
      </el-form>
      <el-button type="primary" plain size="mini" @click="toggleCollapse">{{
        isCollapsed ? "展开" : "收起"
      }}</el-button>
      <!-- <el-button type="primary" plain size="mini" icon="el-icon-plus" @click="addmembers()">新增单项</el-button>
      <el-table v-loading="loading" :data="form.tjProjectList" @selection-change="handleSelectionChange" border
        max-height="275" style="margin: 10px 0">
        <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="项目名称" align="center" prop="proName" width="180px">
          <template slot-scope="scope">
            <el-select filterable v-model="scope.row.proName" placeholder="请选择项目名称" @change="getSelectValue">
              <el-option v-for="(item, index) in allList" :key="index" :label="item.proName" :value="item.proName">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="项目明细" align="center" prop="allSonProName" width="400px" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="原价(元)" align="center" prop="proPrice" width="80px" />
        <el-table-column label="现价(元)" align="center" prop="priceNow" width="80px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.priceNow" autocomplete="off" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-circle-plus-outline" @click="addmembers(scope.row)"
              v-hasPermi="['system:package:edit']" title="新增行"></el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click.native.prevent="Delete(scope.$index)"
              v-hasPermi="['hosp:consumables:remove']" title="删除"></el-button>
          </template>
        </el-table-column>
      </el-table> -->
      <el-row style="display: flex; width: 1300px">
        <el-col>
@@ -590,29 +489,6 @@
            />
          </div>
        </el-col>
        <!--  <el-col :span="6">
          <div
            style="text-align: center; margin-bottom: 10px; margin-top: 10px"
          >
            明细项目列表
          </div>
          <div class="tab3">
            <el-tree
              class="filter-tree"
              v-loading="loading"
              :data="TreedataList"
              node-key="proId"
              :props="defaultProps"
              :filter-node-method="filterNode"
              show-checkbox
              @check-change="handleCurrentChecked1"
              :default-checked-keys="checkedListkey"
              ref="trees"
              :render-content="renderContent"
            >
            </el-tree>
          </div>
        </el-col> -->
        <el-col>
          <div class="grid-content bg-purple">
            <div
@@ -630,11 +506,9 @@
              border
              style="width: 90%; margin-left: 20px"
              height="400"
              :span-method="objectSpanMethod"
            >
              <el-table-column prop="proName" label="检查项目">
              </el-table-column>
              <el-table-column
                prop="priceOrd"
                label="原价"
@@ -644,7 +518,6 @@
              </el-table-column>
              <el-table-column label="折扣" width="100px">
                <template slot-scope="scope">
                  <!-- 只输入纯数字折扣 -->
                  <el-input
                    v-model.number="scope.row.limits"
                    @input="calculateDiscount(scope.row)"
@@ -654,13 +527,12 @@
                    min="0"
                    step="0.1"
                    max="10"
                  >
                  </el-input>
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="priceNow"
                label="优惠价"
                label="现价"
                width="80px"
                align="center"
              >
@@ -677,28 +549,7 @@
                  </el-button>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="proName" label="明细项目" width="260px">
              </el-table-column> -->
              <!-- <el-table-column
                label="操作"
                align="center"
                fixed="right"
                class-name="small-padding fixed-width"
                width="50px"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDeletes(scope.row)"
                    title="删除"
                  ></el-button>
                </template>
              </el-table-column>-->
            </el-table>
            <!-- <h3 style="font-weight: 600">合计:{{ pics }}元</h3> -->
          </div>
        </el-col>
      </el-row>
@@ -709,985 +560,454 @@
      </div>
    </el-dialog>
    <!-- 套餐详情 -->
    <!-- <el-dialog :title="title" :visible.sync="Seachopen" width="500px" append-to-body>
      <template>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0px; width: 60px"></div>
        <el-checkbox-group v-model="newproName" @change="handleCheckedCitiesChange">
          <el-checkbox style="margin: 15px 0px; width: 180px" v-for="item in allList" :label="item.proName"
            :key="item.proId">{{ item.proName }}</el-checkbox>
        </el-checkbox-group>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitcheckbox">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
    <Packages ref="aaa" @add="handleChanges" />
  </div>
</template>
<script>
import Packages from "@/components/Packages";
import { listCategory } from "@/api/mall/category";
import { listKeyword } from "@/api/mall/keyword";
// import { getProParentIdDxList, getProSonDxList } from "@/api/system/tijian";
import {
  getProParentIdDxList,
  search,
  getProSonDxList,
} from "@/api/system/package";
import { Big } from 'big.js'
import Packages from "@/components/Packages"
import { listCategory } from "@/api/mall/category"
import { listKeyword } from "@/api/mall/keyword"
import { search } from "@/api/system/package"
import {
  getPacList,
  getPacInFo,
  listPackage,
  getPackage,
  delPackage,
  addPackage,
  updatePackage,
  getAllPackage,
  updateStatus,
  getAllList,
  updateProject,
  getPacTjProjectList,
  saveOreditTjPacNew,
} from "@/api/system/package";
import { Message } from "element-ui";
import Big from "big.js";
} from "@/api/system/package"
import { Message } from "element-ui"
export default {
  name: "Package",
  dicts: ["sys_normal_disable", "sys_yes_no", "dict_tjtype"],
  components: { Packages },
  data() {
    let checkPhoneNum = (rule, value, callback) => {
      let patter = new RegExp(/^1\s*[3456789]\s*(\d\s*){9}$/);
      if (value == "" && value == undefined && !value) {
        return callback("");
      } else if (value != undefined && value != "") {
        return callback();
      } else if (!patter.test(value)) {
        return callback("");
      }
    };
    return {
      pics: 0,
      filterText: "",
      DataList: [],
      list1: true,
      activeName: "1",
      num: 1,
      checkedObj: {},
      dataObj: {},
      Treedata: [],
      TreedataList: [],
      treedataList: [],
      checkedkey: [],
      checkedListkey: [],
      defaultProps: {
        children: [],
        label: "proName",
      },
      isCollapsed: true, // 默认为折叠状态
      categoryList: [],
      keys: "",
      keywordList: [],
      dataListAll: [],
      // 多选框
      priceNow: "",
      checkAll: false,
      isIndeterminate: true,
      // 遮罩层
      loading: false,
      radio: 3,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 体检套餐表格数据
      packageList: [],
      // 套餐选中的父项
      allpackageList: [],
      // 已选
      newproName: [],
      // 所有体检项目·
      allList: [],
      treeList: [],
      // 所有套餐数据
      // allpackage:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      Seachopen: false,
      checkedNodes: [],
      pacId: "",
      // 总条数
      total: 0,
      total1: 0,
      // 查询参数
      pics: 0, // 原价总和
      DataList: [], // 已选项目列表
      Treedata: [], // 项目树数据
      checkedkey: [], // 树默认选中项
      checkedNodes: [], // 记录选中的节点
      isCollapsed: true, // 折叠状态
      categoryList: [], // 套餐类目
      keywordList: [], // 关键字列表
      keys: "", // 关键字字符串
      loading: false, // 加载状态
      single: true, // 是否单选禁用
      multiple: true, // 是否多选禁用
      showSearch: true, // 显示搜索条件
      packageList: [], // 套餐列表
      allList: [], // 所有体检项目
      title: "", // 弹出层标题
      open: false, // 是否显示弹出层
      total: 0, // 主表格总条数
      total1: 0, // 项目树总条数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pacName: null,
        pacRemark: null,
        tjCategory: null,
      },
      queryParams1: {
        page: 1,
        pageSize: 30,
        nr: "",
      },
      // 表单参数
      form: {
        xianprice: null, // 优惠价
        counterPrice: null, //原价
        limits: 10,
        xianprice: 0, // 现价总和,可手动修改
        limits: 10, // 总折扣
        pacName: "",
        pacStatus: "",
        tjCategory: "",
        isOnSale: "",
        sort: null,
        retailPrice: null,
        keywords: [],
      },
      forms: {},
      youhui: 10,
      // 表单校验
      youhui: 10, // 上方折扣
      defaultProps: {
        children: [],
        label: "proName",
      },
      rules: {
        deleted: [
          { required: true, validator: checkPhoneNum, trigger: "blur" },
        ],
        pacName: [
          { required: true, validator: checkPhoneNum, trigger: "blur" },
        ],
        pacName: [{ required: true, message: "套餐名称不能为空", trigger: "blur" }],
        pacStatus: [
          { required: true, validator: checkPhoneNum, trigger: "change" },
          { required: true, message: "请选择套餐状态", trigger: "change" },
        ],
        // categoryId: [
        //   { required: true, validator: checkPhoneNum, trigger: "change" },
        // ],
        /*  keywords: [
          { required: true, validator: checkPhoneNum, trigger: "change" },
        ], */
        isOnSale: [
          { required: true, validator: checkPhoneNum, trigger: "change" },
          { required: true, message: "请选择是否上架", trigger: "change" },
        ],
        sort: [{ required: true, validator: checkPhoneNum, trigger: "blur" }],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        retailPrice: [
          { required: true, validator: checkPhoneNum, trigger: "blur" },
        ],
        counterPrice: [
          { required: true, validator: checkPhoneNum, trigger: "blur" },
          { required: true, message: "小程序价格不能为空", trigger: "blur" },
        ],
        tjCategory: [
          { required: true, validator: checkPhoneNum, trigger: "blur" },
          { required: true, message: "请选择体检类别", trigger: "change" },
        ],
      },
    };
    }
  },
  // watch: {
  //   filterText(val) {
  //     this.$refs.tree.filter(val);
  //   },
  // },
  created() {
    this.getList();
    this.getKeyword();
    this.getCategory();
    this.getList()
    this.getKeyword()
    this.getCategory()
  },
  methods: {
    toggleCollapse() {
      this.isCollapsed = !this.isCollapsed; // 点击按钮时切换isCollapsed的值
      this.isCollapsed = !this.isCollapsed
    },
    filterNode(value, data) {
      if (!value) return true;
      // return data.proName.indexOf(value) !== -1;
      if (data.proName.indexOf(value) !== -1) {
        return data.proName.indexOf(value) !== -1;
      } else {
        return data.proEngName.indexOf(value) !== -1;
      }
      if (!value) return true
      return (
        data.proName.indexOf(value) !== -1 ||
        (data.proEngName && data.proEngName.indexOf(value) !== -1)
      )
    },
    /** 查询体检套餐列表 */
    getList() {
      this.loading = true;
      this.loading = true
      getPacTjProjectList().then((response) => {
        this.allList = response.data;
        if (this.allList.proStatus === 0) {
          this.allList.proStatus = "启用";
        } else {
          this.allList.proStatus = "停用";
        }
        this.loading = false;
      });
        this.allList = response.data
        this.loading = false
      })
      getPacList(this.queryParams).then((response) => {
        response.rows.forEach((item, index) => {
          item.newID =
            (this.queryParams.pageNum - 1) * this.queryParams.pageSize +
            index +
            1;
        });
        this.total = response.total;
        this.packageList = response.rows;
        this.loading = false;
      });
            1
        })
        this.total = response.total
        this.packageList = response.rows
        this.loading = false
      })
    },
    /** 查询关键字列表 */
    getKeyword() {
      this.loading = true;
      listKeyword(this.queryParams).then((response) => {
        this.keywordList = response.rows;
      });
        this.keywordList = response.rows
      })
    },
    sel(val) {
      let id = val;
      this.keys = "";
      id.forEach((item) => {
        this.keys += item + ",";
      });
      this.keys = val.join(",")
    },
    /** 查询类目列表 */
    getCategory() {
      this.loading = true;
      listCategory(this.queryParams).then((response) => {
        this.categoryList = response.rows;
        console.log(this.categoryList, 9988);
      });
        this.categoryList = response.rows
      })
    },
    shangpin(vals) {},
    // 取消按钮
    cancel() {
      this.open = false;
      this.Seachopen = false;
      this.reset();
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        pacId: null,
        pacName: null,
        pacRemark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        deleted: null,
        allSonName: null,
        allProName: null,
        priceNow: null,
        proId: null,
        // pacStatus: "启用",
      };
      this.resetForm("form");
        pacName: "",
        pacRemark: "",
        pacStatus: "",
        tjCategory: "",
        isOnSale: "",
        sort: null,
        retailPrice: null,
        xianprice: 0,
        limits: 10,
        keywords: [],
      }
      this.DataList = []
      this.checkedkey = []
      this.checkedNodes = []
      this.youhui = 10
      this.pics = 0
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.queryParams.pageNum = 1
      this.getList()
    },
    handlePackage() {
      this.$refs.aaa.open = true;
      this.$refs.aaa.getList();
      this.$refs.aaa.title = "套餐字典";
      this.$refs.aaa.open = true
      this.$refs.aaa.getList()
      this.$refs.aaa.title = "套餐字典"
    },
    handleChanges(param1) {
      this.form.pacName = param1[0].pacName;
      this.form.hisPacId = param1[0].pacId;
      this.form.pacName = param1[0].pacName
      this.form.hisPacId = param1[0].pacId
      if (param1[0].price) {
        this.form.counterPrice = param1[0].price;
        this.form.retailPrice = param1[0].price;
        this.form.counterPrice = param1[0].price
        this.form.retailPrice = param1[0].price
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (!selection[0]) {
        return;
      if (!selection.length) {
        this.forms = null
        this.ids = []
        this.single = true
        this.multiple = true
        return
      }
      this.forms = selection[0];
      this.ids = selection.map((item) => item.pacId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.forms = selection[0]
      this.ids = selection.map((item) => item.pacId)
      this.single = selection.length !== 1
      this.multiple = false
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "体检套餐信息维护";
      this.DataList = [];
      this.checkedkey = [];
      this.checkedListkey = [];
      this.getDataList();
      // getAllList().then((response) => {
      //   this.allList = response.data;
      //   if (this.allList.proStatus === 0) {
      //     this.allList.proStatus = "启用";
      //   } else {
      //     this.allList.proStatus = "停用";
      //   }
      //   this.loading = false;
      // });
      // if (!this.form.tjProjectList) {
      //     this.form.tjProjectList = []
      //     this.form.tjProjectList.push({
      //       id: parseInt(length),
      //       proName: "",
      //       allSonProName: "",
      //       proPrice: "",
      //       priceNow: "",
      //       proId: "",
      //       Selection,
      //     });
      //   }
      this.reset()
      this.open = true
      this.title = "体检套餐信息维护"
      this.getDataList()
    },
    // 是否启用
    handleStatusChange(row) {
      let data = {
        pacId: row.pacId,
        pacStatus: row.pacStatus,
      };
      let text = row.pacStatus === "0" ? "启用" : "停用";
      this.$confirm("确认要" + text + row.pacName + "套餐吗?")
        .then(function () {
          return updateStatus(data);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.pacStatus = row.pacStatus === "0" ? "0" : "1";
        });
    },
    handleUp() {
      this.title = "体检套餐信息维护";
      this.open = true;
      // getPacTjProjectList().then((response) => {
      //   this.allList = response.data;
      //   this.loading = false;
      // });
      getPacInFo(this.forms.pacId).then((response) => {
        this.form = response.data;
        console.log(this.form, 2233);
        this.form.keywords = this.form.keywords.slice(0, -1);
        this.form.keywords = this.form.keywords.split(",");
        // this.DataList = [];
        // this.pics = 0;
        this.DataList = [];
        this.checkedkey = [];
        this.checkedListkey = [];
        this.DataList = response.data.packageProjects;
        this.DataList.forEach((item) => {
          this.checkedkey.push(item.proId);
          this.checkedListkey.push(item.proId);
        });
        // 获取新的数据列表(如果需要)
        this.getDataList();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = "体检套餐信息维护";
      this.open = true;
      getPacInFo(row.pacId).then((response) => {
        this.form = response.data;
        console.log(this.form, 445);
        this.form.keywords = this.form.keywords.slice(0, -1);
        this.form.keywords = this.form.keywords.split(",");
        this.DataList = [];
        this.checkedkey = [];
        this.checkedListkey = [];
        this.DataList = response.data.packageProjects;
        this.DataList.forEach((item) => {
          this.checkedkey.push(item.proId);
          this.checkedListkey.push(item.proId);
        });
        // 获取新的数据列表(如果需要)
        this.getDataList();
      });
    },
    // 新增行
    addmembers() {
      if (this.form.pacName) {
        if (!this.form.tjProjectList) {
          this.form.tjProjectList = [];
          this.form.tjProjectList.push({
            id: parseInt(length),
            proName: "",
            allSonProName: "",
            proPrice: "",
            priceNow: "",
            proId: "",
            Selection,
          });
        } else {
          this.form.tjProjectList.push({
            id: parseInt(length),
            proName: "",
            allSonProName: "",
            proPrice: "",
            priceNow: "",
            proId: "",
            Selection,
          });
        }
      } else {
        Message.warning("请先填写套餐名称");
      }
      this.$forceUpdate();
    },
    // 删除行
    Delete(index) {
      if (this.form.tjProjectList.length == 0) {
        this.$alert("请先选择要删除的数据", "提示", {
          confirmButtonText: "确定",
        });
      } else {
        this.form.tjProjectList.splice(index, 1);
      }
    },
    /** 删除按钮操作 */
    handleDelete1(row) {
      this.DataList = this.DataList.filter((item) => item.proId !== row.proId);
      // 从 checkedNodes 中移除
      const index = this.checkedNodes.indexOf(row.proId);
      if (index > -1) {
        this.checkedNodes.splice(index, 1);
      }
      const tree = this.$refs.tree;
      const node = tree.getNode(row.proId);
      if (node) {
        node.setChecked(false);
      }
      this.updateTotalPrice();
    },
    getSelectValue(val) {
      this.form.tjProjectList.forEach((formitem) => {
        if (formitem.proName == val) {
          formitem.allSonProName = "";
          this.allList.find((item) => {
            if (item.proName == val) {
              formitem.proId = item.proId;
              formitem.proPrice = item.proPrice;
              formitem.priceNow = item.proPrice;
              formitem.allSonProName = item.allSonProName;
              // item.tjProjectList.forEach((item1) => {
              //   this.$nextTick(() => {
              //     formitem.allSonProName =
              //       formitem.allSonProName + "," + item1.proName;
              //   });
              //   // this.form.tjProjectList.allSonProName = this.form.tjProjectList.allSonProName+','+item1.proName
              // });
            }
          });
        }
      });
      for (let i = 0; i < this.form.tjProjectList.length; i++) {
        for (let j = i + 1; j < this.form.tjProjectList.length; j++) {
          if (
            this.form.tjProjectList[i].proId == this.form.tjProjectList[j].proId
          ) {
            this.form.tjProjectList.splice(j, 1);
            j--;
            this.$modal.msgError("此项目已录入,不可重复录入");
          }
        }
      }
      return this.form.tjProjectList;
    },
    numberChange(currentValue, oldValue) {
      this.$confirm("确定修改所有子项的折扣吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.youhui = currentValue;
          this.DataList.forEach((item) => {
            item.limits = this.youhui;
            const proPrice = new Big(item.priceOrd);
            const limits = new Big(item.limits);
            const result = proPrice.times(limits.div(10));
            item.priceNow = result.toNumber();
            this.form.xianprice = this.DataList.reduce((sum, item) => {
              return sum.plus(new Big(item.priceNow || "0"));
            }, new Big(0));
          });
        })
      let data = { pacId: row.pacId, pacStatus: row.pacStatus }
      let text = row.pacStatus === "0" ? "启用" : "停用"
      this.$confirm(`确认要${text}${row.pacName}套餐吗?`)
        .then(() => updateStatus(data))
        .then(() => this.msgSuccess(`${text}成功`))
        .catch(() => {
          this.youhui = oldValue;
        });
          row.pacStatus = row.pacStatus === "0" ? "1" : "0"
        })
    },
    handleUp() {
      this.title = "体检套餐信息维护"
      this.open = true
      getPacInFo(this.forms.pacId).then((response) => {
        this.form = response.data
        this.form.keywords = this.form.keywords
          ? this.form.keywords.slice(0, -1).split(",")
          : []
        this.DataList = response.data.packageProjects || []
        this.checkedkey = this.DataList.map((item) => item.proId)
        this.checkedNodes = [...this.checkedkey]
        this.updateTotalPrice()
        this.updateYouhui()
        this.getDataList()
      })
    },
    handleUpdate(row) {
      this.title = "体检套餐信息维护"
      this.open = true
      getPacInFo(row.pacId).then((response) => {
        this.form = response.data
        this.form.keywords = this.form.keywords
          ? this.form.keywords.slice(0, -1).split(",")
          : []
        this.DataList = response.data.packageProjects || []
        this.checkedkey = this.DataList.map((item) => item.proId)
        this.checkedNodes = [...this.checkedkey]
        this.updateTotalPrice()
        this.updateYouhui()
        this.getDataList()
      })
    },
    handleDelete1(row) {
      this.DataList = this.DataList.filter((item) => item.proId !== row.proId)
      const index = this.checkedNodes.indexOf(row.proId)
      if (index > -1) this.checkedNodes.splice(index, 1)
      const tree = this.$refs.tree
      const node = tree.getNode(row.proId)
      if (node) node.setChecked(false)
      this.updateTotalPrice()
      this.updateYouhui()
    },
    numberChange(currentValue) {
      this.youhui = currentValue
      this.DataList.forEach((item) => {
        item.limits = this.youhui
        this.updateProPrice(item)
      })
      this.updateTotalPrice()
    },
    handleXianPriceInput(value) {
      const numValue = Math.max(0, Number(value) || 0)
      console.log("123")
      this.form.xianprice = numValue
    },
    handleXianPriceChange(newValue) {
      const value = Math.max(0, Number(newValue) || 0)
      if (this.DataList.length === 0 || this.pics === 0) {
        this.form.xianprice = 0
        this.youhui = 10
        return
      }
      // 使用Big.js处理精度
      const totalOriginalPrice = new Big(this.pics)
      const totalCurrentPrice = new Big(value)
      let newYouhui = totalCurrentPrice
        .div(totalOriginalPrice)
        .times(10)
        .toNumber()
      // 限制折扣范围
      newYouhui = Math.min(10, Math.max(0, newYouhui))
      this.youhui = Number(newYouhui.toFixed(1))
      // 更新所有项目的折扣和现价
      this.DataList.forEach((item) => {
        item.limits = this.youhui
        this.updateProPrice(item)
      })
      // 重新计算确保精度
      this.updateTotalPrice(true)
    },
    updateProPrice(row) {
      const proPrice = new Big(row.priceOrd);
      const limits = new Big(row.limits);
      const result = proPrice.times(limits.div(10)); // ordPrice * (discount / 10)
      row.priceNow = result.toNumber();
      this.form.xianprice = this.DataList.reduce((sum, item) => {
        return sum.plus(new Big(item.priceNow || "0"));
      }, new Big(0)).toNumber();
      this.youhui =
        (Math.floor((this.form.xianprice / this.pics) * 100) / 100) * 10;
      // console.log(this.youhui, 1212);
      if (!row.priceOrd) return
      const proPrice = new Big(row.priceOrd)
      const limits = new Big(row.limits || 10)
      row.priceNow = parseFloat(proPrice.times(limits.div(10)).toFixed(2))
    },
    calculateDiscount(row) {
      if (row.limits > 10) {
        row.limits = 10; // 强制将值设置为最大值
      } else if (row.limits < 0) {
        row.limits = 0; // 强制将值设置为最小值
      }
      this.updateProPrice(row); // 更新价格或其他逻辑
      row.limits = Math.min(10, Math.max(0, row.limits))
      this.updateProPrice(row)
      this.updateTotalPrice()
      this.updateYouhui()
    },
    // 默认接受四个值 { 当前行的值, 当前列的值, 行的下标, 列的下标 }
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      let fields = ["propinName"];
      let cellValue = row[column.property];
      if (cellValue && fields.includes(column.property)) {
        let prevRow = this.DataList[rowIndex - 1];
        let nextRow = this.DataList[rowIndex + 1];
        if (prevRow && prevRow[column.property] === cellValue) {
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = this.DataList[++countRowspan + rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
    updateTotalPrice(skipXianPrice = false) {
      // 计算原价总和
      this.pics = this.DataList.reduce(
        (sum, item) => sum + (Number(item.priceOrd) || 0),
        0
      )
      // 计算现价总和
      if (!skipXianPrice) {
        const totalCurrent = this.DataList.reduce(
          (sum, item) => sum + (Number(item.priceNow) || 0),
          0
        )
      console.log("1231")
        this.form.xianprice = parseFloat(totalCurrent).toFixed(2)
      }
    },
    renderContent(h, { node, data, store }) {
    updateYouhui() {
      if (this.DataList.length === 0 || this.pics === 0) {
        this.youhui = 10
        return
      }
      const totalOriginal = new Big(this.pics)
      const totalCurrent = new Big(this.form.xianprice || 0)
      this.youhui = parseFloat(
        totalCurrent
          .div(totalOriginal)
          .times(10)
          .toFixed(1)
      )
    },
    renderContent(h, { node, data }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span>({data.proPrice}元)</span>
        </span>
      );
      )
    },
    getDataList() {
      this.loading = true;
      this.loading = true
      search(this.queryParams1).then((response) => {
        this.Treedata = response.data.list; // 更新树形数据
        this.total1 = response.data.total; // 更新总条数
        this.pics = this.DataList.reduce(
          (total, item) => total + item.priceOrd,
          0
        );
        // 确保在数据加载后保持选中状态
        this.Treedata = response.data.list
        this.total1 = response.data.total
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(this.checkedNodes);
        });
      });
      this.loading = false;
          this.$refs.tree.setCheckedKeys(this.checkedNodes)
        })
        this.loading = false
      })
    },
    // getDataList() {
    //   this.loading = true;
    //   getProParentIdDxList(this.queryParams).then((response) => {
    //     this.Treedata = response.data.list;
    //     /*  if (this.form.tjProjectList) {
    //       this.form.tjProjectList.forEach((item) => {
    //         this.Treedata.forEach((item1) => {
    //           if (item.proId == item1.proId) {
    //             this.checkedkey.push(item1.proId);
    //             this.DataList.push(item1);
    //             this.DataList.forEach((item1) => {
    //               item1.limits = 10;
    //               if (item1.limits > 10) {
    //                 item1.limits = 10; // 强制将值设置为最大值
    //               } else if (item1.limits < 0) {
    //                 item1.limits = 0; // 强制将值设置为最小值
    //               }
    //               this.updateProPrice(item1); // 更新价格或其他逻辑
    //             });
    //           }
    //         });
    //       });
    //     }  */ /* else {
    //       this.checkedkey.push(this.Treedata[0].proId);
    //       let proId = this.Treedata[0].proId;
    //       this.TreedataList = this.Treedata.filter(
    //         (item) => item.proId == proId
    //       ); */
    //     // 将第一个项目添加到 DataList
    //     // this.TreedataList.forEach((item) => {
    //     //   this.checkedListkey.push(item.proId);
    //     //   this.DataList.push(item);
    //     // });
    //     /*  getProSonDxList(proId).then((res) => {
    //         this.TreedataList = res.data.list;
    //         this.TreedataList.forEach((item) => {
    //           item.disabled = true;
    //           this.checkedListkey.push(item.proId);
    //           this.DataList.push(item);
    //           this.DataList.forEach((item) => {
    //             item.propinName = this.Treedata[0].proName;
    //             item.propinPrice = this.Treedata[0].proPrice;
    //           });
    //           this.pics = 0;
    //           this.DataList.forEach((item) => {
    //             this.pics += item.proPrice;
    //           });
    //         });
    //       }); */
    //     // }
    //     this.pics = this.DataList.reduce(
    //       (total, item) => total + item.priceOrd,
    //       0
    //     );
    //     this.loading = false;
    //   });
    // },
    handleFilterInput() {
      this.queryParams1.page = 1; // 搜索时重置为第一页
      this.getDataList(); // 调用接口获取数据
      // 在过滤后,重新设置选中状态
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.checkedNodes);
      });
      this.queryParams1.page = 1
      this.getDataList()
    },
    // 分页事件
    handlePageChange({ page, pageSize }) {
      this.queryParams.page = page; // 更新当前页
      this.queryParams.pageSize = pageSize; // 更新每页条数
      this.getDataList(); // 调用接口获取数据
    },
    handleCurrentChecked(data, checked, indeterminate) {
    handleCurrentChecked(data, checked) {
      if (checked) {
        // 如果已选列表中不存在此项目,则添加
        if (!this.DataList.some((item) => item.proId === data.proId)) {
          this.DataList.push({
          const newItem = {
            proId: data.proId,
            proName: data.proName,
            priceOrd: data.proPrice,
            limits: 10,
            priceNow: data.proPrice,
          });
        }
        // 添加到 checkedNodes 数组
        if (!this.checkedNodes.includes(data.proId)) {
          this.checkedNodes.push(data.proId);
            limits: this.youhui,
            priceNow: 0,
          }
          this.updateProPrice(newItem)
          this.DataList.push(newItem)
          this.checkedNodes.push(data.proId)
        }
      } else {
        // 取消选中时,从DataList中移除
        this.DataList = this.DataList.filter(
          (item) => item.proId !== data.proId
        );
        // 从 checkedNodes 中移除
        const index = this.checkedNodes.indexOf(data.proId);
        if (index > -1) {
          this.checkedNodes.splice(index, 1);
        }
        this.DataList = this.DataList.filter((item) => item.proId !== data.proId)
        const index = this.checkedNodes.indexOf(data.proId)
        if (index > -1) this.checkedNodes.splice(index, 1)
      }
      // 更新优惠价和总价
      this.updateTotalPrice();
      this.updateTotalPrice()
      this.updateYouhui()
    },
    updateTotalPrice() {
      // 计算所有项目的总优惠价
      this.form.xianprice = this.DataList.reduce((sum, item) => {
        return sum.plus(new Big(item.priceNow || "0"));
      }, new Big(0)).toNumber();
      // 计算原价总和
      this.pics = this.DataList.reduce(
        (total, item) => total + item.priceOrd,
        0
      );
    },
    spliceData() {
      for (var i = 0; i < this.DataList.length; i++) {
        for (var j = i + 1; j < this.DataList.length; j++) {
          if (this.DataList[i].proId == this.DataList[j].proId) {
            //如果第一个等于第二个,splice方法删除第二个
            this.DataList.splice(j, 1);
            j--;
          }
        }
      }
      return this.DataList;
    },
    // 点击获取每个树节点
    handleCurrentChecked1(data, checked, checkedNodes) {
      if (checked == false) {
        this.DataList.forEach((item, index) => {
          if (item.proId == data.proId) {
            this.DataList.splice(index, 1);
            this.TotalPrice1 = 0;
            this.pics = 0;
            this.DataList.forEach((item1) => {
              this.pics += item1.priceOrd;
              // this.TotalPrice1 = item1.proPrice + this.TotalPrice1;
            });
          }
        });
      } else if (checked == true) {
        this.DataList.push(data);
        this.pics = 0;
        this.DataList.forEach((item1) => {
          this.pics += item1.priceOrd;
          if (item1.proParentId == this.dataObj.proId) {
            item1.propinName = this.dataObj.proName;
            item1.propinPrice = this.dataObj.proPrice;
          }
        });
        this.spliceData();
        this.TotalPrice1 = 0;
        this.pics = 0;
        this.DataList.forEach((item1) => {
          // this.TotalPrice1 = item1.proPrice + this.TotalPrice1;
          this.pics += item1.priceOrd;
        });
      }
    },
    /** 删除按钮操作 */
    handleDeletes(row) {
      this.DataList.forEach((item, index) => {
        if (item.proParentId == row.proParentId) {
          this.DataList.splice(index, 1);
          this.TotalPrice1 = 0;
          this.DataList.forEach((item1) => {
            this.TotalPrice1 = item1.proPrice + this.TotalPrice1;
          });
        }
      });
      // this.$refs.trees.setCheckedKeys([]);
    },
    /** 提交按钮 */
    submitForm() {
      this.form.limits = this.youhui;
      this.form.price = this.pics;
      this.form.priceNow = this.queryParams.xianprice;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.limits = this.youhui
          this.form.price = this.pics
          this.form.newPrice = this.form.xianprice
      if (this.keys) {
        this.form.keywords = this.keys; // 如果有 this.keys,则直接赋值
      } else {
        // this.form.keywords = this.form.keywords; // 如果没有,则将 this.form.keywords 转成字符串
      }
          const packageProjects = this.DataList.map((item) => ({
            proName: item.proName,
            proId: item.proId,
            priceNow: item.priceNow,
            limits: item.limits,
            priceOrd: item.priceOrd,
          }))
      let packageProjects = []; // 定义一个空数组
      this.DataList.forEach((item) => {
        packageProjects.push({
          proName: item.proName,
          proId: item.proId,
          priceNow: item.priceNow,
          limits: item.limits,
          priceOrd: item.priceOrd,
        });
      });
      let data = {
        pacName: this.form.pacName,
        limits: this.form.limits,
        pacStatus: this.form.pacStatus,
        packageProjects: packageProjects,
        newPrice: this.form.xianprice,
        price: this.pics,
        pacId: this.form.pacId || null,
        isOnSale: this.form.isOnSale,
        // keywords: this.form.keywords,
        sort: this.form.sort,
        retailPrice: this.form.retailPrice,
        tjCategory: this.form.tjCategory,
        pacRemark: this.form.pacRemark,
        detail: this.form.detail,
      };
      saveOreditTjPacNew(data).then((res) => {
        console.log(res, 555);
        this.open = false;
        this.getList();
      });
    },
    /* submitForm() {
      if (this.form.pacName) {
        this.form.tjProjectList = [];
        if (this.DataList.length != 0) {
          this.treeList = JSON.parse(JSON.stringify(this.DataList));
          for (var i = 0; i < this.treeList.length; i++) {
            for (var j = i + 1; j < this.treeList.length; j++) {
              if (
                this.treeList[i].proParentId == this.treeList[j].proParentId
              ) {
                this.treeList.splice(j, 1);
                j--;
              }
            }
          const data = {
            pacName: this.form.pacName,
            limits: this.form.limits,
            pacStatus: this.form.pacStatus,
            packageProjects,
            newPrice: this.form.xianprice,
            price: this.pics,
            pacId: this.form.pacId || null,
            isOnSale: this.form.isOnSale,
            sort: this.form.sort,
            retailPrice: this.form.retailPrice,
            tjCategory: this.form.tjCategory,
            pacRemark: this.form.pacRemark,
            detail: this.form.detail,
            keywords: this.keys,
          }
          this.treeList.forEach((item) => {
            this.form.tjProjectList.push({
              // id: 0,
              proName: item.propinName,
              // allSonProName: item.proName + ",",
              proPrice: item.propinPrice,
              priceNow: item.propinPrice,
              proId: item.proParentId,
            });
          });
          saveOreditTjPacNew(data).then(() => {
            this.open = false
            this.getList()
            this.$modal.msgSuccess("保存成功")
          })
        }
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.pacId != null) {
              // if (this.form.pacStatus === "启用") {
              //   this.form.pacStatus = 0;
              // } else {
              //   this.form.pacStatus = 1;
              // }
              if (this.keys) {
                this.form.keywords = this.keys;
              } else {
                this.form.keywords = this.form.keywords.toString();
              }
              updatePackage(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.keywords = this.keys;
              // if (this.form.pacStatus === "启用") {
              //   this.form.pacStatus = 0;
              // } else {
              //   this.form.pacStatus = 1;
              // }
              // return;
              addPackage(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      } else {
        Message.warning("请先填写套餐名称");
      }
    }, */
    /** 删除按钮操作 */
      })
    },
    handleDelete(row) {
      const pacIds = row.pacId || this.ids;
      const pacIds = row.pacId || this.ids
      this.$modal
        .confirm('是否确认删除体检套餐编号为"' + pacIds + '"的数据项?')
        .then(function () {
          return delPackage(pacIds);
        })
        .confirm(`是否确认删除体检套餐编号为"${pacIds}"的数据项?`)
        .then(() => delPackage(pacIds))
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.getList()
          this.$modal.msgSuccess("删除成功")
        })
        .catch(() => {});
        .catch(() => {})
    },
    /** 分配套餐内项目操作 */
    handleProject: function (row) {
      const pacId = row.pacId;
      this.$router.push("/system/user-auth/role/" + pacId);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/package/export",
        {
          ...this.queryParams,
        },
        { ...this.queryParams },
        `package_${new Date().getTime()}.xlsx`
      );
    },
    // 套餐详情
    // handleSeach(row) {
    //   this.Seachopen = true;
    //   this.loading = true;
    //   const pacId = row.pacId;
    //   this.pacId = row.pacId
    //   let data = {
    //     pacId: pacId,
    //   };
    //   getAllPackage(data).then((response) => {
    //     this.allpackageList = response.data.tjProjectList;
    //     this.loading = false;
    //     let arr = [];
    //     this.allpackageList.forEach((item) => {
    //       arr.push(item.proName);
    //     });
    //     this.newproName = arr;
    //   });
    //   getAllPackageList().then((response) => {
    //     this.allList = response.data;
    //     this.loading = false;
    //   });
    // },
    // // 全选
    // handleCheckAllChange(val) {
    //   this.newproName = val ? this.allList : [];
    //   this.isIndeterminate = false;
    // },
    // handleCheckedCitiesChange(value) {
    //   let checkedCount = value.length;
    //   this.checkAll = checkedCount === this.allList.length;
    //   this.isIndeterminate =
    //     checkedCount > 0 && checkedCount < this.allList.length;
    // },
    submitcheckbox() {
      let _this = this;
      let proIds = [];
      this.allList.forEach((item) => {
        _this.newproName.forEach((item1) => {
          if (item.proName == item1) {
            proIds.push(item.proId);
          }
        });
      });
      let data = {
        pacid: Number(this.pacId),
        proIds: proIds.toString(),
      };
      updateProject(data).then((response) => {
        this.$modal.msgSuccess("成功");
        this.Seachopen = false;
      });
      )
    },
  },
};
}
</script>
<style>
.el-tooltip__popper {
@@ -1723,12 +1043,1046 @@
  overflow-y: auto;
  border: 1px solid #d9d9d9;
}
/* .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  } */
</style><template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="套餐名称" prop="pacName">
        <el-input
          v-model="queryParams.pacName"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐描述" prop="pacRemark">
        <el-input
          v-model="queryParams.pacRemark"
          placeholder="请输入套餐描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="体检类别" prop="tjCategory">
        <el-select
          v-model="queryParams.tjCategory"
          placeholder="请选择状态"
          style="width: 200px"
          filterable
          clearable
        >
          <el-option
            v-for="dict in dict.type.dict_tjtype"
            :key="dict.id"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </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"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:package:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUp"
          v-hasPermi="['system:package:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:package:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:package:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <template>
      <el-table
        v-loading="loading"
        style="width: 100%"
        :data="packageList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column
          fixed
          type="selection"
          width="40"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="序号"
          align="center"
          width="50"
          prop="newID"
          fixed
        />
        <el-table-column
          label="体检类别"
          width="100px"
          align="center"
          prop="categoryNames"
          fixed
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.dict_tjtype"
              :value="scope.row.tjCategory"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="套餐名称"
          align="center"
          prop="pacName"
          width="150px"
          fixed
        />
        <el-table-column
          label="原价"
          width="80px"
          align="center"
          prop="price"
          fixed
        ></el-table-column>
        <el-table-column
          label="折扣"
          width="80px"
          align="center"
          prop="limits"
          fixed
        ></el-table-column>
        <el-table-column
          label="现价"
          width="80px"
          align="center"
          prop="newPrice"
          fixed
        >
        </el-table-column>
        <el-table-column
          label="单项列表"
          align="center"
          prop="allProName"
          width="1200px"
        >
        </el-table-column>
        <el-table-column
          label="套餐描述"
          align="center"
          :show-overflow-tooltip="true"
          width="120px"
        >
          <template slot-scope="scope">
            <div class="showInline">{{ scope.row.pacRemark }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="关键字"
          width="110px"
          align="center"
          prop="keyNames"
        ></el-table-column>
        <el-table-column
          label="是否上架"
          width="94px"
          align="center"
          prop="isOnSale"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sys_yes_no"
              :value="scope.row.isOnSale"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="排序"
          width="50px"
          align="center"
          prop="sort"
        ></el-table-column>
        <el-table-column
          label="小程序价格"
          width="90px"
          align="center"
          prop="retailPrice"
        ></el-table-column>
        <el-table-column
          label="已售数量"
          width="90px"
          align="center"
          prop="saleNum"
        ></el-table-column>
        <el-table-column
          label="状态"
          align="center"
          prop="pacStatus"
          fixed="right"
          width="100px"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.pacStatus"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="80px"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:package:edit']"
              title="修改"
            ></el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:package:remove']"
              title="删除"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pag">
        <div class="pag1">
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
    </template>
    <!-- 修改体检套餐对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1400px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        :inline="true"
      >
        <el-form-item label="套餐名称" prop="pacName">
          <span
            slot="label"
            style="display: inline-block; border-bottom: 2px solid blue"
            @click="handlePackage"
          >
            套餐名称
          </span>
          <el-input
            v-model="form.pacName"
            placeholder="请输入套餐名称"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="套餐状态" prop="pacStatus">
          <el-select
            v-model="form.pacStatus"
            placeholder="请选择状态"
            style="width: 150px"
            filterable
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="体检类别" prop="tjCategory">
          <el-select
            v-model="form.tjCategory"
            placeholder="请选择体检类别"
            style="width: 150px"
            filterable
            clearable
          >
            <el-option
              v-for="dict in dict.type.dict_tjtype"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否上架" prop="isOnSale">
          <el-select
            v-model="form.isOnSale"
            placeholder="请选择是否上架"
            style="width: 140px"
            filterable
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input
            v-model="form.sort"
            placeholder="请输入排序"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="小程序价格" prop="retailPrice">
          <el-input
            v-model="form.retailPrice"
            placeholder="请输入小程序价格"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="原价" prop="pics">
          <el-input
            v-model="pics"
            placeholder="请输入原价"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="折扣">
          <el-input-number
            ref="inputNumber"
            style="width: 150px"
            v-model="youhui"
            :precision="2"
            :step="0.1"
            :max="10"
            :min="1"
            @change="numberChange"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="现价">
          <el-input
            ref="inputName"
            v-model="form.xianprice"
            placeholder="请输入现价"
            clearable
            style="width: 140px"
            type="number"
            :min="0"
            @change="handleXianPriceChange"
            @input="handleXianPriceInput"
          />
        </el-form-item>
        <el-form-item label="关键字" prop="keywords">
          <el-select
            multiple
            v-model="form.keywords"
            placeholder="请选择关键字"
            style="width: 160px"
            @change="sel"
            filterable
            clearable
          >
            <el-option
              v-for="item in keywordList"
              :key="item.id"
              :label="item.keyword"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <div v-if="!isCollapsed" style="display: flex">
          <div>
            <el-form-item label="套餐描述" prop="pacRemark">
              <el-input
                type="textarea"
                v-model="form.pacRemark"
                placeholder="请输入套餐描述"
                style="width: 670px"
                rows="2"
              ></el-input>
            </el-form-item>
            <el-form-item label="详细介绍" prop="detail">
              <editor
                v-model="form.detail"
                :min-height="192"
                style="width: 670px"
              />
            </el-form-item>
          </div>
          <div class="dialo2">
            <el-form-item label="图片">
              <image-upload v-model="form.pacPhone" />
            </el-form-item>
          </div>
        </div>
      </el-form>
      <el-button type="primary" plain size="mini" @click="toggleCollapse">{{
        isCollapsed ? "展开" : "收起"
      }}</el-button>
      <el-row style="display: flex; width: 1300px">
        <el-col>
          <div
            style="text-align: center; margin-bottom: 10px; margin-top: 10px"
          >
            项目列表
          </div>
          <el-input
            placeholder="输入关键字进行过滤"
            @input="handleFilterInput"
            v-model="queryParams1.nr"
            clearable
          />
          <div class="tab3" style="height: 365px">
            <el-tree
              class="filter-tree"
              v-loading="loading"
              :data="Treedata"
              :props="defaultProps"
              show-checkbox
              node-key="proId"
              @check-change="handleCurrentChecked"
              :default-checked-keys="checkedkey"
              :filter-node-method="filterNode"
              ref="tree"
              :render-content="renderContent"
            >
            </el-tree>
            <pagination
              small
              v-show="total1 > 0"
              :total="total1"
              :page.sync="queryParams1.page"
              :limit.sync="queryParams1.pageSize"
              @pagination="getDataList"
            />
          </div>
        </el-col>
        <el-col>
          <div class="grid-content bg-purple">
            <div
              style="
                text-align: center;
                margin-bottom: 10px;
                margin-top: 10px;
                margin-left: 8%;
              "
            >
              已选项目列表
            </div>
            <el-table
              :data="DataList"
              border
              style="width: 90%; margin-left: 20px"
              height="400"
            >
              <el-table-column prop="proName" label="检查项目">
              </el-table-column>
              <el-table-column
                prop="priceOrd"
                label="原价"
                align="center"
                width="80px"
              >
              </el-table-column>
              <el-table-column label="折扣" width="100px">
                <template slot-scope="scope">
                  <el-input
                    v-model.number="scope.row.limits"
                    @input="calculateDiscount(scope.row)"
                    placeholder="输入折扣"
                    size="small"
                    type="number"
                    min="0"
                    step="0.1"
                    max="10"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="priceNow"
                label="现价"
                width="80px"
                align="center"
              >
              </el-table-column>
              <el-table-column label="操作" align="center" width="80px">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete1(scope.row)"
                    title="删除"
                  >
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <Packages ref="aaa" @add="handleChanges" />
  </div>
</template>
<script>
import { Big } from 'big.js'
import Packages from "@/components/Packages"
import { listCategory } from "@/api/mall/category"
import { listKeyword } from "@/api/mall/keyword"
import { search } from "@/api/system/package"
import {
  getPacList,
  getPacInFo,
  delPackage,
  updateStatus,
  getPacTjProjectList,
  saveOreditTjPacNew,
} from "@/api/system/package"
import { Message } from "element-ui"
export default {
  name: "Package",
  dicts: ["sys_normal_disable", "sys_yes_no", "dict_tjtype"],
  components: { Packages },
  data() {
    return {
      pics: 0, // 原价总和
      DataList: [], // 已选项目列表
      Treedata: [], // 项目树数据
      checkedkey: [], // 树默认选中项
      checkedNodes: [], // 记录选中的节点
      isCollapsed: true, // 折叠状态
      categoryList: [], // 套餐类目
      keywordList: [], // 关键字列表
      keys: "", // 关键字字符串
      loading: false, // 加载状态
      single: true, // 是否单选禁用
      multiple: true, // 是否多选禁用
      showSearch: true, // 显示搜索条件
      packageList: [], // 套餐列表
      allList: [], // 所有体检项目
      title: "", // 弹出层标题
      open: false, // 是否显示弹出层
      total: 0, // 主表格总条数
      total1: 0, // 项目树总条数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pacName: null,
        pacRemark: null,
        tjCategory: null,
      },
      queryParams1: {
        page: 1,
        pageSize: 30,
        nr: "",
      },
      form: {
        xianprice: 0, // 现价总和,可手动修改
        limits: 10, // 总折扣
        pacName: "",
        pacStatus: "",
        tjCategory: "",
        isOnSale: "",
        sort: null,
        retailPrice: null,
        keywords: [],
      },
      youhui: 10, // 上方折扣
      defaultProps: {
        children: [],
        label: "proName",
      },
      rules: {
        pacName: [{ required: true, message: "套餐名称不能为空", trigger: "blur" }],
        pacStatus: [
          { required: true, message: "请选择套餐状态", trigger: "change" },
        ],
        isOnSale: [
          { required: true, message: "请选择是否上架", trigger: "change" },
        ],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
        retailPrice: [
          { required: true, message: "小程序价格不能为空", trigger: "blur" },
        ],
        tjCategory: [
          { required: true, message: "请选择体检类别", trigger: "change" },
        ],
      },
    }
  },
  created() {
    this.getList()
    this.getKeyword()
    this.getCategory()
  },
  methods: {
    toggleCollapse() {
      this.isCollapsed = !this.isCollapsed
    },
    filterNode(value, data) {
      if (!value) return true
      return (
        data.proName.indexOf(value) !== -1 ||
        (data.proEngName && data.proEngName.indexOf(value) !== -1)
      )
    },
    getList() {
      this.loading = true
      getPacTjProjectList().then((response) => {
        this.allList = response.data
        this.loading = false
      })
      getPacList(this.queryParams).then((response) => {
        response.rows.forEach((item, index) => {
          item.newID =
            (this.queryParams.pageNum - 1) * this.queryParams.pageSize +
            index +
            1
        })
        this.total = response.total
        this.packageList = response.rows
        this.loading = false
      })
    },
    getKeyword() {
      listKeyword(this.queryParams).then((response) => {
        this.keywordList = response.rows
      })
    },
    sel(val) {
      this.keys = val.join(",")
    },
    getCategory() {
      listCategory(this.queryParams).then((response) => {
        this.categoryList = response.rows
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        pacId: null,
        pacName: "",
        pacRemark: "",
        pacStatus: "",
        tjCategory: "",
        isOnSale: "",
        sort: null,
        retailPrice: null,
        xianprice: 0,
        limits: 10,
        keywords: [],
      }
      this.DataList = []
      this.checkedkey = []
      this.checkedNodes = []
      this.youhui = 10
      this.pics = 0
      this.resetForm("form")
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    handlePackage() {
      this.$refs.aaa.open = true
      this.$refs.aaa.getList()
      this.$refs.aaa.title = "套餐字典"
    },
    handleChanges(param1) {
      this.form.pacName = param1[0].pacName
      this.form.hisPacId = param1[0].pacId
      if (param1[0].price) {
        this.form.counterPrice = param1[0].price
        this.form.retailPrice = param1[0].price
      }
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      if (!selection.length) {
        this.forms = null
        this.ids = []
        this.single = true
        this.multiple = true
        return
      }
      this.forms = selection[0]
      this.ids = selection.map((item) => item.pacId)
      this.single = selection.length !== 1
      this.multiple = false
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "体检套餐信息维护"
      this.getDataList()
    },
    handleStatusChange(row) {
      let data = { pacId: row.pacId, pacStatus: row.pacStatus }
      let text = row.pacStatus === "0" ? "启用" : "停用"
      this.$confirm(`确认要${text}${row.pacName}套餐吗?`)
        .then(() => updateStatus(data))
        .then(() => this.msgSuccess(`${text}成功`))
        .catch(() => {
          row.pacStatus = row.pacStatus === "0" ? "1" : "0"
        })
    },
    handleUp() {
      this.title = "体检套餐信息维护"
      this.open = true
      getPacInFo(this.forms.pacId).then((response) => {
        this.form = response.data
        this.form.keywords = this.form.keywords
          ? this.form.keywords.slice(0, -1).split(",")
          : []
        this.DataList = response.data.packageProjects || []
        this.checkedkey = this.DataList.map((item) => item.proId)
        this.checkedNodes = [...this.checkedkey]
        this.updateTotalPrice()
        this.updateYouhui()
        this.getDataList()
      })
    },
    handleUpdate(row) {
      this.title = "体检套餐信息维护"
      this.open = true
      getPacInFo(row.pacId).then((response) => {
        this.form = response.data
        this.form.keywords = this.form.keywords
          ? this.form.keywords.slice(0, -1).split(",")
          : []
        this.DataList = response.data.packageProjects || []
        this.checkedkey = this.DataList.map((item) => item.proId)
        this.checkedNodes = [...this.checkedkey]
        this.updateTotalPrice()
        this.updateYouhui()
        this.getDataList()
      })
    },
    handleDelete1(row) {
      this.DataList = this.DataList.filter((item) => item.proId !== row.proId)
      const index = this.checkedNodes.indexOf(row.proId)
      if (index > -1) this.checkedNodes.splice(index, 1)
      const tree = this.$refs.tree
      const node = tree.getNode(row.proId)
      if (node) node.setChecked(false)
      this.updateTotalPrice()
      this.updateYouhui()
    },
    numberChange(currentValue) {
      this.youhui = currentValue
      this.DataList.forEach((item) => {
        item.limits = this.youhui
        this.updateProPrice(item)
      })
      this.updateTotalPrice()
    },
    handleXianPriceInput(value) {
      const numValue = Math.max(0, Number(value) || 0)
      this.form.xianprice = numValue
    },
    handleXianPriceChange(newValue) {
      const value = Math.max(0, Number(newValue) || 0)
      if (this.DataList.length === 0 || this.pics === 0) {
        this.form.xianprice = 0
        this.youhui = 10
        return
      }
      // 使用Big.js处理精度
      const totalOriginalPrice = new Big(this.pics)
      const totalCurrentPrice = new Big(value)
      let newYouhui = totalCurrentPrice
        .div(totalOriginalPrice)
        .times(10)
        .toNumber()
      // 限制折扣范围
      newYouhui = Math.min(10, Math.max(0, newYouhui))
      this.youhui = Number(newYouhui.toFixed(1))
      // 更新所有项目的折扣和现价
      this.DataList.forEach((item) => {
        item.limits = this.youhui
        this.updateProPrice(item)
      })
      // 重新计算确保精度
      this.updateTotalPrice(true)
    },
    updateProPrice(row) {
      if (!row.priceOrd) return
      const proPrice = new Big(row.priceOrd)
      const limits = new Big(row.limits || 10)
      row.priceNow = parseFloat(proPrice.times(limits.div(10)).toFixed(2))
    },
    calculateDiscount(row) {
      row.limits = Math.min(10, Math.max(0, row.limits))
      this.updateProPrice(row)
      this.updateTotalPrice()
      this.updateYouhui()
    },
    updateTotalPrice(skipXianPrice = false) {
      // 计算原价总和
      this.pics = this.DataList.reduce(
        (sum, item) => sum + (Number(item.priceOrd) || 0),
        0
      )
      // 计算现价总和
      if (!skipXianPrice) {
        const totalCurrent = this.DataList.reduce(
          (sum, item) => sum + (Number(item.priceNow) || 0),
          0
        )
        this.form.xianprice = parseFloat(totalCurrent).toFixed(2)
      }
    },
    updateYouhui() {
      if (this.DataList.length === 0 || this.pics === 0) {
        this.youhui = 10
        return
      }
      const totalOriginal = new Big(this.pics)
      const totalCurrent = new Big(this.form.xianprice || 0)
      this.youhui = parseFloat(
        totalCurrent
          .div(totalOriginal)
          .times(10)
          .toFixed(1)
      )
    },
    renderContent(h, { node, data }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span>({data.proPrice}元)</span>
        </span>
      )
    },
    getDataList() {
      this.loading = true
      search(this.queryParams1).then((response) => {
        this.Treedata = response.data.list
        this.total1 = response.data.total
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(this.checkedNodes)
        })
        this.loading = false
      })
    },
    handleFilterInput() {
      this.queryParams1.page = 1
      this.getDataList()
    },
    handleCurrentChecked(data, checked) {
      if (checked) {
        if (!this.DataList.some((item) => item.proId === data.proId)) {
          const newItem = {
            proId: data.proId,
            proName: data.proName,
            priceOrd: data.proPrice,
            limits: this.youhui,
            priceNow: 0,
          }
          this.updateProPrice(newItem)
          this.DataList.push(newItem)
          this.checkedNodes.push(data.proId)
        }
      } else {
        this.DataList = this.DataList.filter((item) => item.proId !== data.proId)
        const index = this.checkedNodes.indexOf(data.proId)
        if (index > -1) this.checkedNodes.splice(index, 1)
      }
      this.updateTotalPrice()
      this.updateYouhui()
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.limits = this.youhui
          this.form.price = this.pics
          this.form.newPrice = this.form.xianprice
          const packageProjects = this.DataList.map((item) => ({
            proName: item.proName,
            proId: item.proId,
            priceNow: item.priceNow,
            limits: item.limits,
            priceOrd: item.priceOrd,
          }))
          const data = {
            pacName: this.form.pacName,
            limits: this.form.limits,
            pacStatus: this.form.pacStatus,
            packageProjects,
            newPrice: this.form.xianprice,
            price: this.pics,
            pacId: this.form.pacId || null,
            isOnSale: this.form.isOnSale,
            sort: this.form.sort,
            retailPrice: this.form.retailPrice,
            tjCategory: this.form.tjCategory,
            pacRemark: this.form.pacRemark,
            detail: this.form.detail,
            keywords: this.keys,
          }
          saveOreditTjPacNew(data).then(() => {
            this.open = false
            this.getList()
            this.$modal.msgSuccess("保存成功")
          })
        }
      })
    },
    handleDelete(row) {
      const pacIds = row.pacId || this.ids
      this.$modal
        .confirm(`是否确认删除体检套餐编号为"${pacIds}"的数据项?`)
        .then(() => delPackage(pacIds))
        .then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        })
        .catch(() => {})
    },
    handleExport() {
      this.download(
        "system/package/export",
        { ...this.queryParams },
        `package_${new Date().getTime()}.xlsx`
      )
    },
  },
}
</script>
<style>
.el-tooltip__popper {
  max-width: 800px;
}
.showInline {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}
.pag {
  width: 100%;
  display: flex;
  justify-content: center;
}
.pag1 {
  width: 30%;
}
.dialog-footer {
  position: absolute;
  left: 40%;
  bottom: 2%;
}
.tab3 {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #d9d9d9;
}
</style>