<template>
  <div class="app-container">
    <div class="header">
      <div class="btns">
        <el-button @click="goback">取消</el-button>
        <el-button type="primary" @click="signupload">签约</el-button>
      </div>
      <el-descriptions title="签约详情" class="descriptions"> </el-descriptions>
      <el-descriptions title="患者信息" style="padding: 0 30px">
        <el-descriptions-item label="患者姓名">{{
          $route.query.patientName
        }}</el-descriptions-item>
        <el-descriptions-item label="性别"
          >{{ $route.query.sex == "MALE" ? "男" : ""
          }}{{ $route.query.sex == "FEMALE" ? "女" : "" }}</el-descriptions-item
        >
        <!-- <el-descriptions-item label="年龄">{{ $route.query.age }}</el-descriptions-item> -->
        <el-descriptions-item label="电话">{{
          $route.query.patientPhone
        }}</el-descriptions-item>
        <el-descriptions-item label="就诊方式"
          >{{
            $route.query.visitMethod == "OUTPATIENT_SERVICE"
              ? "门诊"
              : $route.query.visitMethod == "BE_IN_HOSPITAL"
              ? "住院"
              : ""
          }}
        </el-descriptions-item>
        <el-descriptions-item label="诊断">{{
          $route.query.signDiagnosis
        }}</el-descriptions-item>
        <el-descriptions-item label="住院/门诊号">{{
          $route.query.inHospitalNumber
        }}</el-descriptions-item>
        <el-descriptions-item label="医院">{{
          $route.query.hospitalAgencyName
        }}</el-descriptions-item>
        <el-descriptions-item label="科室">{{
          $route.query.departmentName
        }}</el-descriptions-item>
        <!-- <el-descriptions-item label="出院/门诊时间">{{ $route.query.patientName }}</el-descriptions-item> -->
        <!-- <el-descriptions-item label="注册时间">{{ $route.query.patientName }}</el-descriptions-item> -->
      </el-descriptions>
      <el-descriptions
        title="健康管理师信息"
        style="padding: 20px 30px 10px"
        class="descriptions"
      >
      </el-descriptions>
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="110px"
        class="demo-ruleForm"
        :inline="true"
        style="padding-left: 40px"
      >
        <el-form-item label="健康管理师" required>
          <el-select
            v-model="form.record.healthManageId"
            filterable
            placeholder="请选择健康管理师"
            style="width: 300px"
            clearable
          >
            <el-option
              v-for="item in attendingPhysicianlist"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-descriptions
        title="服务包信息"
        style="padding: 20px 30px 10px"
        class="descriptions"
      >
      </el-descriptions>
      <el-form
        :model="signPackage"
        :rules="rules"
        ref="signPackage"
        label-width="110px"
        class="demo-ruleForm"
        :inline="true"
        style="padding-left: 40px"
      >
        <el-form-item label="选择服务包" prop="servicePackageId">
          <el-button
            @click="tappackage()"
            style="
              width: 208px;
              text-align: left;
              height: 36px;
              overflow: hidden;
            "
            :style="
              form.servicePackageName == '请选择服务包' ? 'color: #c0c4cc;' : ''
            "
            >{{ form.servicePackageName }}</el-button
          >
        </el-form-item>

        <!-- <el-select v-model="signPackage.servicePackageId" filterable placeholder="请选择服务包" clearable
                        @change="tappackage">
                        <el-option v-for="item in packagelist" :key="item.id" :label="item.packageName"
                            :value="item.id">
                        </el-option>
                    </el-select> -->
        <!-- </el-form-item> -->
        <el-form-item
          label="服务包缴费状态"
          prop="packagePaymentStatus"
          label-width="130px"
        >
          <el-select
            v-model="signPackage.packagePaymentStatus"
            filterable
            placeholder="请选择服务包"
            clearable
          >
            <el-option label="已缴费" value="PAID"> </el-option>
            <el-option label="未缴费" value="UNPAID_FEES"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form
        :model="signPackage"
        :rules="rules"
        ref="signPackage"
        label-width="80px"
        class="demo-ruleForm"
        :inline="true"
        style="padding-left: 40px"
      >
        <el-form-item label="签约期限" prop="" label-width="110px">
          <div>
            <el-input
              v-model="signPackage.packageTerm"
              style="width: 130px"
              disabled
              placeholder="请输入签约周期"
            ></el-input>
            <el-select
              v-model="signPackage.packageTermUnit"
              style="width: 110px"
              placeholder="周期单位"
              disabled
            >
              <el-option label="年" value="年">年</el-option>
              <el-option label="月" value="月">月</el-option>
              <el-option label="日" value="日">日</el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="服务时长" prop="packageName">
          <el-date-picker
            v-model="signPackage.serviceStartTime"
            type="date"
            disabled
            placeholder="开始日期"
            style="width: 150px"
          >
          </el-date-picker>
          至
          <el-input
            v-model="signPackage.serviceEndTime"
            style="width: 150px"
            disabled
            placeholder="结束日期"
          ></el-input>
        </el-form-item>
        <el-form-item label="服务包价格(元)" prop="" label-width="120px">
          <el-input
            v-model="signPackage.packagePrice"
            style="width: 150px"
            disabled
            oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)} if(value.length>7){value=value.slice(0,7)}"
            min="0"
            placeholder="小数点后两位(元)"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-descriptions
        title="专病管理信息"
        style="padding: 20px 30px 10px"
        class="descriptions"
      >
      </el-descriptions>
      <el-form
        :model="route"
        :rules="rules"
        ref="route"
        label-width="110px"
        class="demo-ruleForm"
        :inline="true"
        style="padding-left: 40px"
      >
        <el-form-item label="专病管理路径" prop="routeId">
          <specialDiseaseRoute
            @on-template="ontemplate"
            v-if="form.servicePackageId"
            :servicePackageId="signPackage.servicePackageId"
            :routeName="route.routeName"
            :routeId="route.routeId"
          >
          </specialDiseaseRoute>
          <el-button
            size="small"
            @click="noservicePackageId"
            v-else
            style="
              width: 200px;
              font-size: 14px;
              color: #c0c4cc;
              text-align: left;
            "
          >
            请选择专病管理路径</el-button
          >
        </el-form-item>
      </el-form>
      <el-descriptions
        title="硬件信息"
        style="padding: 20px 30px 10px"
        class="descriptions"
      >
      </el-descriptions>
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="110px"
        class="demo-ruleForm"
        :inline="true"
        style="padding-left: 40px"
      >
        <div v-for="(item, index) in form.devices" :key="index">
          <el-form-item
            label="硬件类型"
            :prop="`devices[${index}].hardwareType`"
            :rules="rules.devices.hardwareType"
          >
            <el-select
              v-model="item.hardwareType"
              placeholder="请选择硬件类型"
              clearable
              style="width: 208px"
            >
              <el-option
                v-for="dict in dict.type.hardware_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="SN码"
            :prop="`devices[${index}].snCode`"
            :rules="rules.devices.snCode"
          >
            <el-input
              v-model="item.snCode"
              placeholder="请输入设备SN码"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" @click="delhardware(index)">删除</el-button>
          </el-form-item>
        </div>
        <el-button
          class="addbtn"
          type="primary"
          size="mini"
          @click="addhardware"
          >新增硬件</el-button
        >
      </el-form>
      <el-descriptions
        title="知情同意书"
        style="padding: 20px 30px 10px"
        class="descriptions"
      >
      </el-descriptions>
      <el-upload
        :action="upload.url"
        list-type="picture-card"
        style="margin-left: 70px"
        :data="upload.data"
        ref="upload"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :headers="upload.headers"
        :on-success="handleSuccess"
        :auto-upload="false"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <!-- 服务包弹框 -->
      <el-dialog
        title=""
        :visible.sync="innerVisibleshow"
        width="1000px"
        append-to-body
        :before-close="innerVisiblecancel"
      >
        <div style="padding-bottom: 23px">
          <el-form
            ref="queryForm"
            :model="queryParams"
            :rules="rules"
            label-width="80px"
            :inline="true"
          >
            <el-form-item label="病种名称" prop="diseaseTypeName">
              <el-input
                v-model="queryParams.diseaseTypeName"
                placeholder="请输入病种名称"
                clearable
                @keyup.enter.native="getList"
              />
            </el-form-item>
            <el-form-item label="服务包名称" prop="packageName">
              <el-input
                v-model="queryParams.packageName"
                placeholder="请输入服务包名称"
                clearable
                @keyup.enter.native="getList"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="getList"
                >搜索</el-button
              >
              <el-button
                icon="el-icon-refresh"
                size="mini"
                @click="addresetQuerylist"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
            :data="servicepackageList"
            @cell-dblclick="nurseclick"
          >
            <!-- <el-table :max-height="maxTableHeight" v-loading="loading" :data="servicepackageList"
            @selection-change="handleSelectionChange"> -->
            <el-table-column label="序号" align="center" type="index" />
            <el-table-column
              label="服务包名称"
              align="center"
              prop="packageName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="版本号"
              align="center"
              prop="packageVersion"
            />
            <el-table-column
              label="服务期限"
              align="center"
              prop="packageTermAndUnit"
            />
            <el-table-column
              label="服务包简介"
              align="center"
              prop="packageIntroduction"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="备注" align="center" prop="packageRemark" />
            <el-table-column
              label="是否发布"
              align="center"
              prop="whetherRelease"
            >
              <template slot-scope="scope">
                <el-tag type="warning" v-if="scope.row.whetherRelease == '0'"
                  >未发布</el-tag
                >
                <el-tag
                  type="success"
                  v-else-if="scope.row.whetherRelease == '1'"
                  >已发布</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              label="病种名称"
              align="center"
              prop="diseaseTypeName"
            />
            <el-table-column
              width="180"
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <!-- <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-open"
                  @click="copy(scope.row)"
                  >复制</el-button
                > -->
                <!-- <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-promotion"
                  @click="release(scope.row)"
                  v-if="scope.row.whetherRelease == 0"
                  >发布</el-button
                > -->
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-notebook-2"
                  @click="detail(scope.row)"
                  >详情</el-button
                >
                <!-- <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['manage:servicepackage:edit']"
                  v-if="
                    !scope.row.sourceTemplateId ||
                    scope.row.sourceTemplateId == 0
                  "
                  >修改</el-button
                > -->
                <!-- <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['manage:servicepackage:remove']"
                  >删除</el-button
                > -->
              </template>
            </el-table-column>
            <!-- </el-table> -->
          </el-table>
        </div>
        <myPagination
          v-show="totaldepartment > 0"
          :total="totaldepartment"
          :pageSize="queryParams.pageSize"
          :indexFromWrap="queryParams.pageNum"
          @updateCPage="updateCPagetwo"
        ></myPagination>
        <!-- <pagination v-show="totaldepartment > 0" :total="totaldepartment" :page.sync="informationqueryParams.pageNum"
        :limit.sync="informationqueryParams.pageSize" @pagination="informationInfoinfo" /> -->
      </el-dialog>
       <!-- 详情弹框 -->
    <el-dialog title="详情" :visible.sync="detailshow" width="60%" :before-close="handleClose">
      <el-form ref="form" :model="formdetail" label-width="150px" :inline="true">
        <el-form-item label="病种名称:" prop="packageVersion">
          <div class="container">
            <el-tooltip class="item" effect="dark" :content="formdetail.diseaseTypeName" placement="top-start">
              <span>{{ formdetail.diseaseTypeName }}</span>
            </el-tooltip>
          </div>
          <!-- <span style="display: inline-block; width: 120px">
            {{ formdetail.diseaseTypeName }}</span> -->
        </el-form-item>
        <el-form-item label="服务包名称:" prop="packageVersion">
          <div class="container">
            <el-tooltip class="item" effect="dark" :content="formdetail.packageName" placement="top-start">
              <span>{{ formdetail.packageName }}</span>
            </el-tooltip>
          </div>
        </el-form-item>
        <el-form-item label="价格:" prop="packageVersion">
          <span>{{ formdetail.packagePrice }}元</span>
        </el-form-item>
        <br />
        <el-form-item label="服务期限:" prop="packageVersion">
          <span style="display: inline-block; width: 120px">
            {{ formdetail.packageTermAndUnit }}
          </span>
        </el-form-item>
        <el-form-item label="硬件类型:" prop="packageVersion">
          <span>
            {{ formdetail.hardwareType == "BLOOD_PRESSURE" ? "血压仪" : "" }}
          </span>
          <span>
            {{ formdetail.hardwareType == "GLUCOSE_METER" ? "血糖仪" : "" }}
          </span>
          <span>
            {{ formdetail.hardwareType == "ELECTROCARDIOGRA" ? "心电仪" : "" }}
          </span>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="datailList">
        <el-table-column label="序号" type="index" />
        <el-table-column label="服务方式" align="center" prop="serviceWayName" />
        <el-table-column label="服务内容" align="center" prop="serviceContent" :show-overflow-tooltip="true" />
        <el-table-column label="服务频次" align="center" prop="serviceFrequencyText" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailshow = false">关闭</el-button>
      </span>
    </el-dialog>
    </div>
  </div>
</template>

<script>
import { addsign } from "@/api/manage/newSigning.js";
import { listServicepackage,getServicepackage } from "@/api/manage/servicepackage";

import { servicepackageinfo } from "@/api/manage/signRecord.js";
import { getToken } from "@/utils/auth";
import { obtainendtime } from "@/utils/obtainendtime";
import specialDiseaseRoute from "../components/specialDiseaseRoute";
import { usergetList } from "@/api/unitconfig/patientConfiguration";
export default {
  components: { specialDiseaseRoute },
  dicts: ["hardware_type"],
  name: "NewSigning",
  data() {
    return {
      formdetail: {},
      detailshow:false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // departmentId: null,
        departmentName: null,
        diseaseTypeId: null,
        diseaseTypeName: null,
        packageName: null,
        packageIntroduction: null,
        packageVersion: null,
        packageTerm: null,
        packageTermUnit: null,
        packagePrice: null,
        packageRemark: null,
        hardwareType: null,
        departmentId: this.$route.query.departmentId,
        whetherRelease: 1,
      },

      totaldepartment: 0,
      signPackage: {
        packageName: undefined,
        packagePrice: undefined,
        serviceCycle: undefined,
        serviceStartTime: undefined,
        serviceEndTime: "",
        packagePaymentStatus: "",
      },
      route: {
        routeId: undefined,
        routeName: "",
      },
      form: {
        signCategory: "sign",
        record: {
          patientId: undefined,
          patientPhone: undefined,
          healthManageId: "",
          healthManageName: "",
        },
        devices: [
          {
            snCode: undefined,
            hardwareType: undefined,
          },
        ],
        informeds: [],
      },
      rules: {
        packagePaymentStatus: [
          { required: true, message: "缴费状态不能为空", trigger: "change" },
        ],
        servicePackageId: [
          { required: true, message: "请选择服务包", trigger: "change" },
        ],
        healthManageId: [
          { required: true, message: "请选择健康管理师", trigger: "change" },
        ],
        routeId: [
          { required: true, message: "请选择专病管理路径", trigger: "change" },
        ],
        devices: {
          // snCode: [
          //     { required: true, message: '请输入SN码', trigger: 'change' }
          // ],
          // hardwareType: [
          //     { required: true, message: '请选择硬件类型', trigger: 'change' }
          // ],
        },
      },
      upload: {
        data: {
          type: "signInformedFileUrl",
        },
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        url: process.env.VUE_APP_BASE_API + "/manage/file/uploadFile",
      },
      packagelist: [],
      attendingPhysicianlist: [],
      servicepackageList: [],
      servicePackageName:'',
      innerVisibleshow:false,
      datailList:[],
    };
  },
  created() {
    this.form.record = this.$route.query;
    this.signPackage.packagePaymentStatus = this.form.record.paymentStatus;
    this.getList();
    this.usergetListinfo();
  },
  methods: {
     // 详情关闭
     handleClose() {
      this.detailshow = false
    },
     // 详情
     detail(row) {
      this.detailshow = true
      getServicepackage(row.id).then(response => {
        this.formdetail = response.data;
        this.datailList = response.data.voList
        this.datailList.forEach(el => {
          if (el.serviceFrequencyEnd) {
            el.serviceFrequencyText = el.serviceFrequencyStart + '~' + el.serviceFrequencyEnd
          } else {
            el.serviceFrequencyText = el.serviceFrequencyText
          }
        })
      });
    },
     // 科室名称重置
     addresetQuerylist() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.getList();
    },
    innerVisiblecancel() {
      this.innerVisibleshow = false;
    },
       // 科室名称圆点按钮
       nurseclick(row) {
           this.route.routeId = "";
      this.route.routeName = "";
      let item = this.servicepackageList.find((e) => e.id == row.id);
      console.log(item,'item')
      this.signPackage = { ...this.signPackage, ...item };
      let datetime = new Date();
      let year = datetime.getFullYear();
      let month = datetime.getMonth() + 1;
      let day = datetime.getDate();
      month >= 1 && month <= 9 ? (month = "0" + month) : "";
      day >= 0 && day <= 9 ? (day = "0" + day) : "";
      this.signPackage.serviceStartTime = `${year}-${month}-${day}`;
      this.signPackage.serviceEndTime = obtainendtime(
        this.signPackage.serviceStartTime,
        item
      );
      this.form.servicePackageId = row.id;
      this.form.servicePackageName = row.packageName;
      this.servicePackageName = row.packageName;
     
      this.innerVisibleshow = false;
    },
    /** 查询服务包基础信息列表 */
    getList() {
      this.loading = true;
      listServicepackage(this.queryParams).then((response) => {
        this.servicepackageList = response.rows;
        this.totaldepartment = response.total;
        this.loading = false;
      });
    },
    updateCPagetwo(index, size) {
      this.queryParams.pageNum = index;
      this.queryParams.pageSize = size;
      this.getList();
    },
    // 列表查询服务包
    signlist() {
      servicepackageinfo({
        departmentId: this.$route.query.departmentId,
        whetherRelease: 1,
      }).then((res) => {
        this.packagelist = res.data;
        this.totaldepartment=res.data.length
        console.log(res.data,'res.data.length')
      });
    },
    // 点击科室
    clickinnerVisible() {
      this.innerVisibleshow = true;
      this.informationInfoinfo();
    },
    //主治医生
    usergetListinfo() {
      usergetList({
        postName: "HEALTH_MANAGE_MASTER",
      }).then((res) => {
        this.attendingPhysicianlist = res.data;
      });
    },
    ontemplate(item) {
      this.route.routeId = item.routeId;
      this.route.routeName = item.routeName;
    },
    tappackage() {
      this.innerVisibleshow = true;
this.getList()
    //   this.route.routeId = "";
    //   this.route.routeName = "";
    //   let item = this.packagelist.find((e) => e.id == id);
    //   this.signPackage = { ...this.signPackage, ...item };
    //   let datetime = new Date();
    //   let year = datetime.getFullYear();
    //   let month = datetime.getMonth() + 1;
    //   let day = datetime.getDate();
    //   month >= 1 && month <= 9 ? (month = "0" + month) : "";
    //   day >= 0 && day <= 9 ? (day = "0" + day) : "";
    //   this.signPackage.serviceStartTime = `${year}-${month}-${day}`;
    //   this.signPackage.serviceEndTime = obtainendtime(
    //     this.signPackage.serviceStartTime,
    //     item
    //   );
    },
    //签约
    signupload() {
      const files = this.$refs.upload.uploadFiles;
      if (files.length > 0) {
        this.$refs.upload.submit();
      } else {
        this.uploadsave();
      }
    },
    uploadsave() {
      this.$confirm("是否确认签约?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        if (this.signPackage.servicePackageId && this.packagelist?.length > 0) {
          this.signPackage.packageName = this.packagelist.find(
            (e) => e.id == this.signPackage.servicePackageId
          )?.packageName;
        }
        if (
          this.form.record.healthManageId &&
          this.attendingPhysicianlist?.length > 0
        ) {
          this.form.record.healthManageName = this.attendingPhysicianlist.find(
            (e) => e.userId == this.form.record.healthManageId
          )?.nickName;
        }
        this.form.signPackage = this.signPackage;
        this.form.route = this.route;
        addsign(this.form).then((res) => {
          this.$confirm("签约成功, 是否返回上一页?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "success",
          })
            .then(() => {
              this.$store
                .dispatch("tagsView/delView", this.$route)
                .then(({ visitedViews }) => {
                  this.$router.push({
                    path: "/patient/signRecord",
                  });
                });
            })
            .catch(() => {
              this.$modal.msgSuccess("签约成功");
            });
        });
      });
    },
    //文件上传完成
    handleSuccess(response, file, fileList) {
      this.form.informeds = [];
      fileList.forEach((e) => {
        this.form.informeds.push({
          informedFilePath: e.response.imgUrl,
        });
      });
      this.uploadsave();
    },
    //新增硬件
    addhardware() {
      this.form.devices.push({
        snCode: "",
        hardwareType: "",
      });
    },
    delhardware(index) {
      this.form.devices.splice(index, 1);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {},
    goback() {
      this.$store
        .dispatch("tagsView/delView", this.$route)
        .then(({ visitedViews }) => {
          this.$router.push({
            path: "/patient/signRecord",
          });
        });
    },
    noservicePackageId() {
      this.$message.error("请先选择服务包！！");
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 14px 0 0;
  background-color: #f2f3f5 !important;
  width: 100%;

  .descriptions {
    padding: 20px 20px 10px;
  }

  .descriptions {
    ::v-deep .el-descriptions-item__label.has-colon::after {
      display: none;
    }
  }

  .header {
    background-color: #fff;
    width: 98%;
    margin: 0 auto;
    border-radius: 8px;
    height: calc(100% - 5px);
    overflow: auto;
  }

  .btns {
    position: absolute;
    top: 30px;
    right: 30px;
  }

  .addbtn {
    margin-right: 100px;
    float: right;
    transform: translateY(-200%);
  }
}
</style>
