<template>
  <div class="box">
    <div style="position: relative;">
      <div class="middlebox">
        <div class="contenttitle">
          常用设置 /
          <span class="contenttitleBold">套餐设置</span>
        </div>
      </div>
      <!--套餐信息-->
      <div style="display: block; margin-top: 7px;margin-right: 110px;">
        <div style="margin-bottom: 15px;background-color: #fff;padding: 15px;border-radius: 8px;">
          <el-table :data="medicalPackages" ref="medicalPackages" row-key="id" :height="window.pageHeight < 600
              ? 210
              : Math.floor((window.pageHeight - 220) / 2)
            " highlight-current-row :row-class-name="handleRowClassName" @row-click="rowClick">
            <el-table-column type="index" label="序号" min-width="50" align="center" />
            <el-table-column prop="displayName" label="名称" min-width="150" />
            <el-table-column prop="price" label="价格" min-width="60" align="center" />
            <el-table-column prop="forSexId" label="适用性别" min-width="60" align="center">
              <template slot-scope="scope">
                {{ dddw(dict.forSex, "id", scope.row.forSexId, "displayName") }}
              </template>
            </el-table-column>
            <!--
              <el-table-column
                prop="maritalStatusId"
                label="适用婚姻状况"
                min-width="80"
                align="center"
              >
                <template slot-scope="scope">
                  {{
                    dddw(
                      dict.forMaritalStatus,
                      "id",
                      scope.row.maritalStatusId,
                      "displayName"
                    )
                  }}
                </template>
              </el-table-column>
               -->
            <el-table-column prop="isActive" label="启用" min-width="60" align="center">
              <template slot-scope="scope">
                {{ scope.row.isActive == 'Y' ? '是' : '否' }}
              </template>
            </el-table-column>

            <el-table-column prop="creatorName" label="创建者" min-width="60" align="center" />
            <el-table-column label="创建时间" min-width="150" align="center">
              <template slot-scope="scope">
                {{
                  scope.row.creationTime
                  ? moment(scope.row.creationTime).format("yyyy-MM-DD HH:mm:ss")
                  : ""
                }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="40">
              <template>
                <el-tag class="move" style="
                          cursor: move;
                          background-color: rgb(245, 245, 245);
                          border: none;
                        " draggable="true">
                  <i class="el-icon-d-caret" style="
                            width: 1rem;
                            height: 1rem;
                            color: rgb(113, 113, 113);
                          "></i>
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!--套餐项目信息-->
        <div style="background-color: #fff; border-radius: 8px; padding: 15px;position: relative;">
          <MedicalPackageAsbitem :formData="form" :refreshMoney="refreshMoney" />
        </div>
      </div>
      <!--按钮-->
      <div style="margin-left: 10px; margin-top: 40px;position: absolute;top: 0;right: 0;">
        <div>
          <el-button class="commonbutton" @click="btnAdd">新增</el-button>
        </div>
        <div style="margin-top: 10px">
          <el-button class="commonbutton" @click="btnEdit">编辑</el-button>
        </div>
        <div style="margin-top: 10px">
          <el-button class="commonbutton" @click="btnDel">删除</el-button>
        </div>
        <div style="margin-top: 10px">
          <el-button class="commonbutton" @click="btnSetTop">置顶</el-button>
        </div>
        <div style="margin-top: 10px">
          <el-button class="commonbutton" @click="btnSetBottom">置低</el-button>
        </div>
        <div style="margin-top: 10px">
          <el-button class="commonbutton" @click="btnSort" :disabled="!isDrag">保存排序</el-button>
        </div>
      </div>
    </div>

    <!-- 新增或者编辑弹框 -->
    <el-dialog :title="form.id ? '编辑' : '新增'" :close-on-click-modal="false" :visible.sync="dialogVisible" width="800px">
      <el-form :model="form" label-width="80px" :rules="rules" ref="form">
        <el-row>
          <el-col :span="8">
            <el-form-item prop="displayName" label="套餐名称">
              <el-input v-model="form.displayName" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="金额">
              <el-input v-model="form.price" type="number" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="适用性别">
              <el-select v-model="form.forSexId" placeholder="请选择" size="small">
                <el-option v-for="item in dict.forSex" :key="item.id" :label="item.displayName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!--
          <el-col :span="8">            
            <el-form-item label="婚姻状况">
              <el-select
                v-model="form.maritalStatusId"
                placeholder="请选择"
                style="width: 100%" size="small" >
                <el-option
                  v-for="item in dict.forMaritalStatus"
                  :key="item.id"
                  :label="item.displayName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          -->
          <el-col :span="8">
            <el-form-item label="启用" prop="isActive">
              <el-radio v-model="form.isActive" label="Y">是</el-radio>
              <el-radio v-model="form.isActive" label="N">否</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注">
              <el-input v-model="form.remark" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="difference">取消</el-button>
        <!--
        <el-button type="success" @click="computePrice">同比折算套餐项目价格</el-button>
        -->
        <el-button type="primary" @click="onSubmit('form')" class="commonbutton">确定</el-button>
      </span>
    </el-dialog>
    <!--  -->
  </div>
</template>
<script>
import moment from "moment";
import Sortable from "sortablejs";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { mapState } from "vuex";
import { dddw, deepCopy, objCopy, arrayExistObj } from "../../utlis/proFunc";

import MedicalPackageAsbitem from "../../components/common/MedicalPackageAsbitem.vue";

export default {
  components: {
    MedicalPackageAsbitem,
  },
  data() {
    return {
      medicalPackages: [], //套餐
      medicalPackageId: "", //当前选中的体检单位id
      customerOrgRegisterList: [], //体检次数列表
      customerOrgRegister: {}, //体检次数

      isDrag: false,
      form: {
        id: "",
        displayName: "",
        price: 0,
        forSexId: "A",
        // maritalStatusId: "A",
        isActive: 'Y',
        remark: "",
      },
      formOri: {},
      formInit: {},
      rules: {
        displayName: [
          { required: true, message: "请填写套餐名称", trigger: "blur" },
        ],
      },

      dialogVisible: false,

    };
  },
  computed: {
    ...mapState(["personnelUnit", "window", "dict"]),
  },
  created() {
    this.rowDrop();
    this.formInit = deepCopy(this.form);
  },
  mounted() {
    //获取初始数据（单位、适用性别）
    this.dictInit();
  },
  methods: {
    moment,
    dddw, deepCopy,

    //刷新套餐价格（供子组件调用）
    refreshMoney(formData) {
      //console.log('this is parent')
      let lfind = arrayExistObj(this.medicalPackages, 'id', formData.id)
      if (lfind > -1) this.medicalPackages[lfind].price = formData.price
    },

    //确定排序
    btnSort() {
      const result = [];
      this.medicalPackages.forEach((item, index) => {
        result.push({ id: item.id, displayOrder: index + 1 });
      });
      putapi("/api/app/medicalpackage/updatesortmany", {
        itemList: result,
      }).then((res) => {
        if (res.code != -1) {
          this.isDrag = false;
          this.$message.success('操作成功')
        }
      });
    },

    //初始化Sortable组件
    rowDrop() {
      this.$nextTick(() => {
        const el = document.querySelector(".el-table__body-wrapper tbody");
        //console.log('el0',el)
        const that = this;
        Sortable.create(el, {
          handle: ".move",
          animation: 300,
          //拖拽结束
          onEnd({ newIndex, oldIndex }) {
            that.isDrag = true;
            const currRow = that.medicalPackages.splice(oldIndex, 1)[0];
            that.medicalPackages.splice(newIndex, 0, currRow);
          },
        });
      });
    },


    //置底
    btnSetBottom() {
      if (!this.form.id) {
        this.$message.warning("请选择操作的数据");
        return
      }
      let lfind = arrayExistObj(this.medicalPackages, 'id', this.form.id)
      let currentRow = {}

      putapi(
        `/api/app/medicalpackage/updatemanysort?id=${this.form.id}&SortType=2`
      ).then((res) => {
        if (res.code != -1) {
          currentRow = this.medicalPackages.splice(lfind, 1)[0]  //删除并赋值
          this.medicalPackages.push(currentRow)
          this.$refs['medicalPackages'].setCurrentRow(currentRow);
          this.$message.success('操作成功')
        }
      });

    },

    //置顶
    btnSetTop() {
      if (!this.form.id) {
        this.$message.warning("请选择操作的数据");
        return
      }

      let lfind = arrayExistObj(this.medicalPackages, 'id', this.form.id)
      let currentRow = {}

      putapi(
        `/api/app/medicalpackage/updatemanysort?id=${this.form.id}&SortType=1`
      ).then((res) => {
        if (res.code != -1) {
          currentRow = this.medicalPackages.splice(lfind, 1)[0]
          this.medicalPackages.unshift(currentRow)
          this.$refs['medicalPackages'].setCurrentRow(currentRow);
          this.$message.success('操作成功')
        }
      });

    },

    //选中颜色
    handleRowClassName({ row, rowIndex }) {
      // highLightBg 为 'selected'的高亮 
      //console.log(rowIndex, row)
      //return row.highLightBg == 'selected' ? 'high-light-bg' : '';
      if (row.choosed) {
        return 'current-row';
      } else {
        return '';
      }

    },

    //获取初始数据
    dictInit() {

      //获取适用性别
      getapi("/api/app/for-sex").then((res) => {
        if (res.code != -1) {
          this.dict.forSex = res.data;
        }
      });
      this.getPackages()
    },

    getPackages() {
      // /api/app/medicalpackage/getlist      
      postapi("/api/app/medicalpackage/getmedicalpackagelist", {}).then(res => {
        if (res.code != -1) {
          this.medicalPackages = res.data
        }
      })
    },

    //点击套餐
    rowClick(row) {
      objCopy(row, this.form);
      this.formOri = Object.assign({}, row)
    },

    //新增弹框
    btnAdd() {
      // if (!this.customerOrgRegister.id) {
      //   this.$message.warning("请选择体检次数");
      //   return;
      // }
      // if (this.customerOrgRegister.isComplete.toUpperCase() == 'Y') {
      //   this.$message.warning("该单位体检次数已完成，不允许新增套餐");
      //   return;
      // }

      // if (this.customerOrgRegister.isComplete.toUpperCase() == "Y") {
      //   this.$message.warning("该单位的该次体检次数已完成，不能再添加套餐！");
      //   return;
      // }

      this.form = deepCopy(this.formInit);
      // this.form.customerOrgRegisterId = this.customerOrgRegister.id;
      // this.form.medicalPackageId = this.medicalPackageId;
      this.dialogVisible = true;
    },

    //编辑弹框
    btnEdit() {
      if (!this.form.id) {
        this.$message.warning("请选择需要操作的数据");
        return;
      }
      this.dialogVisible = true;
    },

    //删除
    btnDel() {
      if (!this.form.id) {
        this.$message.warning("请选择需要操作的数据");
        return;
      }

      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "  否  ",
        type: "warning",
        cancelButtonClass: "difference",
        confirmButtonClass: "commonbutton"
      }).then(() => {
        return postapi(`/api/app/medicalpackage/delete?id=${this.form.id}`);
      }).then((res) => {
        if (res.code != -1) {
          let lfind = arrayExistObj(
            this.medicalPackages,
            "id",
            this.form.id
          );
          if (lfind > -1) this.medicalPackages.splice(lfind, 1);
          objCopy(this.formInit, this.form)
          this.isDrag = false
          this.$message.success('删除成功')
        }
      }).catch((err) => {
        if (err == "cancel") {
          this.$message.info("已取消删除");
        }
      });
    },

    onSubmit(formName) {
      this.$refs[formName].validate((valid, fields) => {
        if (!valid) {
          this.$message.warning(fields[Object.keys(fields)[0]][0].message);
          return false;
        }

        let body = deepCopy(this.form);
        delete body.id;


        if (this.form.id) {
          let medicalPackageId = this.form.id
          let medicalPackageAsbitems = [] //分组包含的套餐

          //编辑
          postapi(`/api/app/medicalpackage/update?id=${this.form.id}`, body).then(res => {
            if (res.code != -1) {
              let lfind = arrayExistObj(
                this.medicalPackages,
                "id",
                this.form.id
              );
              if (lfind > -1) objCopy(this.form, this.medicalPackages[lfind]);
              if (this.formOri.price != this.form.price) {
                return postapi('/api/app/medicalpackagedetail/getmedicalpackageinasbitem', { medicalPackageId })
              }
            }
          }).then(res => {
            if (res.code != -1) {
              medicalPackageAsbitems = res.data;
              if (medicalPackageAsbitems.length < 1) {
                this.dialogVisible = false;
                this.$message.success('操作成功！')
              } else {
                let detailsBody = {
                  medicalPackageId,
                  details: this.madeNewPackageAsbitems(medicalPackageAsbitems, this.form.price)
                }
                return postapi('/api/app/medicalPackagedetail/createmedicalPackagedetailmany', detailsBody)
              }
            }
          }).then(res => {
            if (res.code != -1) {
              this.$message.success('操作成功！并自动按总价同比折算组合项目价格！')
              this.dialogVisible = false;
              // 刷新明细
              let id = this.form.id
              this.form.id = ''
              setTimeout(() => {
                this.form.id = id
              }, 100);
            }
          });

        } else {
          //新增
          postapi(
            "/api/app/medicalpackage/create",
            body
          ).then((res) => {
            if (res.code != -1) {
              this.form.id = res.data.id;
              this.medicalPackages.push(deepCopy(res.data));
              this.$refs['medicalPackages'].setCurrentRow(this.medicalPackages[this.medicalPackages.length - 1]);
              this.dialogVisible = false;
              this.$message.success('操作成功！')
            }
          });
        }
      });
    },
    computePrice() {
      if (!this.form.id) {
        this.$message.warning("尚未保存信息，不可执行此操作！")
        return
      }
      let medicalPackageId = this.form.id
      let medicalPackageAsbitems = [] //套餐包含的套餐


      postapi('/api/app/medicalPackagedetail/getmedicalPackagedetailinasbitem', { medicalPackageId })
        .then(res => {
          if (res.code != -1) {
            medicalPackageAsbitems = res.data;

            if (medicalPackageAsbitems.length < 1) {
              this.$message.warning("当前套餐尚未设置组合项目，不可执行此操作！")
            } else {
              let body = {
                medicalPackageId,
                details: this.madeNewPackageAsbitems(medicalPackageAsbitems, this.form.price)
              }
              return postapi('/api/app/medicalPackagedetail/createmedicalPackagedetailmany', body)
            }
          }
        }).then(res => {
          if (res.code != -1) {
            //console.log("操作成功");
            //触发套餐明细刷新
            this.form.id = ''
            //要做延时处理，否则不会触发监听
            setTimeout(() => {
              this.form.id = medicalPackageId;
              this.onSubmit('form')
            }, 100)

          }
        })

    },

    madeNewPackageAsbitems(oldPackageAsbitems, newTotal) {
      newTotal = Math.round(Number(newTotal) * 100) / 100
      let newPackageAsbitems = []
      let oldTotal = Number(0)
      oldPackageAsbitems.forEach(e => {
        oldTotal += Number(e.asbitemMoney) //medicalPackageDetailMoney
      })
      oldTotal = Math.round(Number(oldTotal) * 100) / 100

      let discount = 0
      if (oldTotal != 0) discount = Math.round(newTotal * 10000 / oldTotal) / 100

      oldTotal = Number(0)
      oldPackageAsbitems.forEach(e => {
        e.medicalPackageDetailPrice = Math.round(e.price * discount) / 100
        e.medicalPackageDetailMoney = Math.round(e.medicalPackageDetailPrice * e.medicalPackageDetailAmount * 100) / 100
        oldTotal += Number(e.medicalPackageDetailMoney)
      })
      oldTotal = Math.round(Number(oldTotal) * 100) / 100

      //console.log('discount,oldTotal',discount,oldTotal)

      let didTotal = Math.round(Number(newTotal - oldTotal) * 100) / 100
      if (didTotal != 0) {
        for (let i = 0; i < oldPackageAsbitems.length; i++) {
          if (oldPackageAsbitems[i].medicalPackageDetailAmount == 1) {
            oldPackageAsbitems[i].medicalPackageDetailPrice = Math.round((Number(oldPackageAsbitems[i].medicalPackageDetailPrice) + Number(didTotal)) * 100) / 100
            break
          }
        }
      }

      oldPackageAsbitems.forEach(e => {
        newPackageAsbitems.push({
          medicalPackageId: this.form.id, // e.medicalPackageId,
          asbitemId: e.id, // e.asbitemId
          price: e.medicalPackageDetailPrice,
          amount: e.medicalPackageDetailAmount
        })
      })

      return newPackageAsbitems
    },

  },
};
</script>
<style scoped>
@import "../../assets/css/global_button.css";
@import "../../assets/css/global_dialog.css";
@import "../../assets/css/global_table.css";
@import "../../assets/css/global_form.css";
@import "../../assets/css/global_input.css";
@import "../../assets/css/global.css";

.box {
  display: flex;
  flex-direction: column;
}

:deep .el-form-item {
  margin-bottom: 14px;
}

/* 去掉input textarea的手动扩张样式 */
:deep(.el-textarea__inner) {
  resize: none;
}

/* el-dialog的头部样式 */
:deep .el-dialog__header {
  padding: 11px 20px 11px;
}

/* el-dialog的主体样式 */
:deep .el-dialog__body {
  padding: 0px 20px 0px;
}

/* el-divider样式 */
:deep .el-divider--horizontal {
  margin: 0px 0 12px;
}

/* el-dialog的底部样式 */
:deep .el-dialog__footer {
  padding: 0px 20px 14px;
}
</style>