<template>
  <div class="record-list-wrapper">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond"></bread-crumb>
    <div class="record-list-content f-main-content screenSet">
      <div class="page-title">录入管理</div>
      <div class="search-div">
        <div class="search-input">
          <el-form
            ref="serchForm"
            :model="searchData"
            :inline="true"
            label-suffix=":"
            label-width="125px"
            size="small"
          >
            <el-form-item label="履约计划名称">
              <el-input
                v-model="searchData.planName"
                placeholder="请输入关键词"
                style="width: 250px"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="履约时间范围">
              <el-date-picker
                v-model="timeRangeList"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                clearable
                style="width:400px;"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="searchData.nickname" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input
                v-model="searchData.mobilePhone"
                placeholder="请输入手机号"
                maxlength="11"
                clearable
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="search-btn">
          <el-button class="button-green" size="small" type="primary" @click="search(1)">查询</el-button>
          <el-button class="button-white" size="small" plain @click="reseat">重置</el-button>
        </div>
      </div>
      <div class="table-content">
        <el-radio-group v-model="activeName" @change="handlerClick" size="small">
          <el-radio-button label>全部({{recordList.count}})</el-radio-button>
          <el-radio-button label="2">已完成({{recordList.finishedCount}})</el-radio-button>
          <el-radio-button label="1">未完成({{recordList.unfinishedCount}})</el-radio-button>
        </el-radio-group>
        <el-table :data="recordList.enteringDtos" style="width: 100%;margin-top: 20px;">
          <el-table-column prop="nickname" label="姓名" min-width="100" align="center">
            <template slot-scope="scope">
              <!--<span style="cursor: pointer" @click="visitDetail(scope.row)">{{scope.row.nickname}}</span>-->
              <el-button type="text" @click="visitDetail(scope.row)">{{scope.row.nickname}}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="mobilePhone" label="手机号" min-width="100" align="center"></el-table-column>
          <el-table-column prop="name" label="履约计划名称" min-width="150" align="center"></el-table-column>
          <el-table-column prop="followupType" label="履约时间" min-width="200" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.fuPlanInfo}}</span>
              <br />
              <span v-if="scope.row.fuPlanExecuteTime">{{scope.row.fuPlanExecuteTime}}</span>
              <span
                v-if="!scope.row.fuPlanExecuteTime && scope.row.appointmentTime"
              >{{scope.row.appointmentTime}}</span>
              <br />
              <span
                v-if="!scope.row.fuPlanExecuteTime && !scope.row.appointmentTime"
              >{{scope.row.fuPlanTime}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="履约状态" min-width="100" align="center">
            <template slot-scope="scope">
              <span
                :class="scope.row.status == 1 ? 'status-span': ''"
              >{{ scope.row.status | statusFileter }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" min-width="210">
            <template slot-scope="scope">
              <el-button class="btn-right-class" type="text" @click="editRow(scope.row)">履约录入</el-button>|
              <el-button
                class="btn-right-class"
                type="text"
                @click="changeStatusRow(scope.row)"
              >变更履约状态</el-button>
              <!--|<el-button type="text" @click="sendRow(scope.row)">发送患教</el-button>-->
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" class="margin-top20">
          <el-pagination
            background
            v-if="hasData"
            @size-change="handleSizeChangePre"
            @current-change="handleCurrentChangePre"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="paginationSet.pageNo"
            :page-sizes="paginationSet.pageSizes"
            :page-size="paginationSet.pageSize"
            :total="paginationSet.total"
          ></el-pagination>
        </el-row>
      </div>
    </div>
    <followup-detail
      :dialogFormVisible="dialogDetailShow"
      @closeDetail="closeDetail"
      :enteringInfo="enteringInfo"
    ></followup-detail>
    <change-followup-status
      :isShowChangeDialog="isShowChangeDialog"
      :statusForm="statusForm"
      @closeChangeStatus="closeChangeStatus"
    ></change-followup-status>
    <el-dialog
      title="选择量表"
      :visible.sync="selectFormShow"
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="400px"
      :before-close="closeForm"
    >
      <div class="list-content">
        <p
          v-for="(item, index) in formList.scalesList"
          :key="index"
          @click="goFormView(item)"
        >{{item.sendContent}}</p>
      </div>
    </el-dialog>
    <!-- 协议提醒 -->
    <el-dialog
      class="prot-dialog"
      title="提醒"
      :visible.sync="isShowProtocolDialog1"
      width="30%"
      center
      :show-close="false"
    >
      <p class="prot-dialog-tips-1">根据相关规定，在您开展履约项目前，需要居民授权同意《云鹊平台隐私政策》与《知情同意书》，否则将导致履约量表部分信息无法录入</p>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="isShowProtocolDialog1 = false">我知道了</el-button>
      </span>
    </el-dialog>
    <!-- 敏感词及协议校验 -->
    <el-dialog class="prot-dialog" title="提醒" :visible.sync="isShowProtocolDialog" width="30%" center :show-close=false>
      <p class="prot-dialog-tips-1">由于该居民尚未同意{{protocolsStr}}，将导致履约量表敏感信息暂时无法录入。<span v-show="!isSentedProt">为了方便您的工作开展，请您发送短信提醒居民完成授权。</span></p>
      <p v-show="!isSentedProt" class="prot-dialog-tips-1">是否发送短信提醒居民？</p>
      <p v-show="isSentedProt" class="prot-dialog-tips-2">您已发送短信提醒该居民同意授权。继续录入，您只能录入量表的非敏感信息。</p>
      <span v-show="!isSentedProt" slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeProtocolDialog"> 暂不发送 </el-button>
        <el-button size="small" type="primary" @click="sendMsg"> 发送短信 </el-button>
      </span>
      <span v-show="isSentedProt" slot="footer" class="dialog-footer">
        <!--<el-button size="small" type="primary" @click="closeProtocolDialog"> 我知道了 </el-button>-->
        <el-button size="small" @click="closeProtocolDialog"> 继续录入 </el-button>
        <el-button size="small" type="primary" @click="isShowProtocolDialog = false"> 暂不录入 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BreadCrumb from "@/components/breadcrumb";
import followupDetail from "./dialog/followupDetail";
import ChangeFollowupStatus from "./dialog/change-followup-status";
import { getSaasDomain } from "@/utils/index";
import { getFirstAccess, uniteValidate, authMessage } from '@/utils/followup/followapis'
import { mapState, mapGetters, mapActions } from "vuex";

export default {
  components: {
    BreadCrumb,
    followupDetail,
    ChangeFollowupStatus
  },
  data() {
    return {
      curmbFirst: "履约管理",
      curmbSecond: "录入管理",
      timeRangeList: [],
      searchData: {
        planName: "",
        beginTime: "",
        endTime: "",
        nickname: "",
        mobilePhone: ""
      },
      activeName: "",
      paginationSet: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [10, 20, 50, 100]
      },
      statusForm: {},
      enteringRow: {},
      dialogDetailShow: false,
      isShowChangeDialog: false,
      hasData: false,
      selectFormShow: false,
      ScaleData: {},
      isShowProtocolDialog1: false,
      isShowProtocolDialog: false,
      scaleQuery: {},
      isSentedProt: false,
      scaleNo: '',
      patientIds: [],
      sendMsgPatientIds: [],
      protocolsStr: '',
    };
  },
  computed: {
    ...mapState("recordManage", {
      recordList: state => state.recordList,
      enteringInfo: state => state.enteringInfo,
      formList: state => state.formList
    }),
    ...mapGetters(["_token"])
  },
  created() {
    // 验证是否首次进入     ################
    // this.init();
    this.search(1);
  },
  mounted() {
    this.isFirstEnter();
  },
  methods: {
    ...mapActions("recordManage", [
      "getRecordList",
      "getEnteringInfo",
      "getFormList"
    ]),

    // 验证是否首次进入 ################
    isFirstEnter() {
      getFirstAccess().then((res) => {
        if(res.code == '000000') {
          this.isShowProtocolDialog1 = res.data
        }
      });
    },
    async search(currentPage) {
      if (this.timeRangeList) {
        this.searchData.beginTime = this.timeRangeList[0];
        this.searchData.endTime = this.timeRangeList[1];
      } else {
        this.searchData.beginTime = "";
        this.searchData.endTime = "";
      }
      await this.getRecordList({
        ...this.searchData,
        status: this.activeName,
        pageNo: currentPage || this.paginationSet.pageNo,
        pageSize: this.paginationSet.pageSize
      });
      if (this.recordList.enteringDtos) {
        if (this.recordList.enteringDtos.length > 0) {
          this.hasData = true;
        } else {
          this.hasData = false;
        }
      }
      const {
        pageNo,
        pageSize,
        count,
        finishedCount,
        unfinishedCount
      } = this.recordList;
      if (this.activeName == "") {
        this.paginationSet.total = count;
      } else if (this.activeName == 2) {
        this.paginationSet.total = finishedCount;
      } else if (this.activeName == 1) {
        this.paginationSet.total = unfinishedCount;
      }
      this.paginationSet = {
        ...this.paginationSet,
        pageNo,
        pageSize: pageSize
      };
    },
    reseat() {
      this.searchData.planName = "";
      this.searchData.nickname = "";
      this.searchData.mobilePhone = "";
      this.timeRangeList = [];
      this.searchData.beginTime = "";
      this.searchData.endTime = "";
      this.search(1);
    },
    async visitDetail(row) {
      await this.getEnteringInfo({
        patientId: row.patientId,
        fuPlanPatientTimesId: row.fuPlanPatientTimesId
      });
      this.dialogDetailShow = true;
      // this.enteringRow = row;
    },
    closeDetail(val) {
      this.dialogDetailShow = val;
    },
    handlerClick() {
      this.search(1);
    },
    async editRow(row) {
      await this.getFormList({planTimesId: row.fuPlanTimesId, planPatientTimesId: row.fuPlanPatientTimesId}); //获取量表列表
      //获取量表列表情况
      this.patientIds = [row.patientId];
      if (this.formList.scalesList.length > 1) {
        this.selectFormShow = true;
        this.ScaleData = {
          doctorId: this.formList.doctorId,
          planPatientsTimesId: row.fuPlanPatientTimesId
        };
      } else if (this.formList.scalesList.length === 1) {
        // this.$router.push({
        //   path: "/followup/record-manage/form-template",
        //   query: {
        //     doctorId: this.formList.doctorId,
        //     scaleNo: this.formList.scalesList[0].resourceId,
        //     planPatientsTimesId: row.fuPlanPatientTimesId,
        //     planTimesId: row.planTimesId,
        //     showBtn: 1
        //   }
        // });
        this.scaleQuery = {
          doctorId: this.formList.doctorId,
          scaleNo: this.formList.scalesList[0].resourceId,
          planPatientsTimesId: row.fuPlanPatientTimesId,
          planTimesId: row.planTimesId,
          showBtn: 1
        }
        this.scaleNo = this.formList.scalesList[0].resourceId;
        this.uniteValidateAction()

      } else {
        this.$message.warning("暂无量表!");
      }
      //  不区分量表列表长度问题，直接调试量表录入
      //   this.$router.push({
      //     name: 'formTemplate',
      //     params: {
      //       data: row
      //     }
      //   })
    },
    changeStatusRow(row) {
      this.statusForm = row;
      this.isShowChangeDialog = true;
    },
    sendRow(row) {
      let saasUrl = getSaasDomain(
        `/pica-frontend/patientEduManage/pica_patient_edu_manage.html#/pageTab/message?patientId=${row.patientId}&nickname=${row.nickname}&token=${this._token}`
      );
      // let saasUrl = getSaasDomain(`/pica-frontend/patientEduManage/pica_patient_edu_manage.html#/pageTab/message?patientId=${row.patientId}&nickname=${row.nickname}&token=8143DC2A026B4602BF7B746FB5AEE9A1`);
      window.open(saasUrl);
    },
    handleSizeChangePre(pageSize) {
      this.paginationSet["pageSize"] = pageSize;
      this.paginationSet["pageNo"] = 1;
      this.search();
    },
    handleCurrentChangePre(pageNo) {
      this.paginationSet["pageNo"] = pageNo;
      this.search();
    },
    closeChangeStatus(val) {
      this.isShowChangeDialog = val;
      this.search();
      // let getArguments = arguments[0];
      // this.isShowChangeDialog = getArguments[0];
      // this.statusForm = getArguments[1];
    },
    goFormView(item) {
      this.selectFormShow = false;
      // this.$router.push({
      //   path: "/followup/record-manage/form-template",
      //   query: {
      //     doctorId: this.ScaleData.doctorId,
      //     scaleNo: item.resourceId,
      //     planPatientsTimesId: this.ScaleData.planPatientsTimesId,
      //     planTimesId: item.planTimesId,
      //     showBtn: 1
      //   }
      // });
      this.scaleQuery = {
        doctorId: this.ScaleData.doctorId,
        scaleNo: item.resourceId,
        planPatientsTimesId: this.ScaleData.planPatientsTimesId,
        planTimesId: item.planTimesId,
        showBtn: 1
      };
      this.scaleNo = item.resourceId;
      // this.patientIds = [this.ScaleData.patientId];
      this.uniteValidateAction();
    },
    closeForm() {
      this.selectFormShow = false;
    },

    // Add by Anndy Yang
    // 统一验证：量表内是否存在敏感字段、居民是否签署隐私协议、7天内是否发送过授权短信
    uniteValidateAction() {
      let validParams = {
        scaleNo: this.scaleNo,
        patientIds: this.patientIds, // pc端只传这个字段
        // planPatientsTimesId: planPatientsTimesId,  // app端只传这个字段
        protocolType: 5,
        userType: 1,
        validateType: 1
      };

      uniteValidate(validParams).then(res => {
        let result = res;
        // 请求成功
        if (result.code === '000000') {
          let levelType = result.data.levelType;
          let protocols = result.data.protocols; //该居民未同意的隐私协议
          if(protocols && protocols.length > 0) {
            this.protocolsStr = protocols.join('、');
          }
          // 没有敏感字段或者居民已经签订过协议，则直接返回
          if (levelType === 1 || levelType === 2) {
            this.jumpToScale();
          } else if (levelType === 3) {
            this.isShowProtocolDialog = true;
            this.isSentedProt = true;
          } else if (levelType === 4) {
            this.isShowProtocolDialog = true;
            this.isSentedProt = false;
            this.sendMsgPatientIds = result.data.ids;
          }
        }
      });
    },

    // 发送协议授权短信给居民
    sendMsgToPatients() {
      authMessage({ patientIds: this.sendMsgPatientIds }).then(res => {
        if (res.code === '000000') {
          this.$message({
            // message: '已发送，请尽快联系居民同意授权',
            message: '短信发送成功',
            type: 'success'
          });
        }
      });
      this.isShowProtocolDialog = false;
    },

    // 统一跳转到量表页面
    jumpToScale() {
      this.$router.push({
        path: "/followup/record-manage/form-template",
        query: this.scaleQuery
      });
    },

    // 关闭协议确认窗口
    closeProtocolDialog() {
      this.isShowProtocolDialog = false
      this.jumpToScale()
    },

    // 发送短信通知
    sendMsg() {
      this.sendMsgToPatients();
      this.closeProtocolDialog()
    },

  },
  filters: {
    statusFileter: function(value) {
      if (!value && value != 0) {
        return "";
      } else {
        let hash = {
          1: "未完成",
          2: "已完成"
        };
        return hash[value];
      }
    }
  }
};
</script>

<style scoped lang="scss">
@import "../../../style/followup/followup-common";
@import "../../../style/followup/element-reset.css";
.record-list-wrapper {
  .record-list-content {
    .search-input {
      max-width: none;
      flex: 1;
    }
    .margin-top20 {
      margin-top: 20px;
    }
    .status-span {
      color: $picaGreen;
    }
  }
  .list-content {
    p {
      cursor: pointer;
      line-height: 30px;
      text-decoration: underline;
      color: $picaGreen;
    }
  }
}
</style>
