<template>
  <div class="plan-modify">
    <div class="bread-crumb">
      <el-breadcrumb separator="/" >
        <el-breadcrumb-item v-for="item in planModifyCrumb">
          <a v-if="item.href" :href="item.href">{{item.name}}</a>
          <span v-else >{{item.name}}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="new-plan-content f-main-content screenSet" id="screenSet">
      <div class="header">
        <div class="title">
          <span>修改计划</span>
        </div>
        <div class="plan-btns-group">
          <el-button class="button-white" plain @click="cancelEdit" size="small">取 消</el-button>
          <el-button class="button-green" type="primary" @click="saveModify" size="small">保 存</el-button>
        </div>
      </div>
      <el-form ref="baseInfo" :model="planDetailData" :rules="rules" label-suffix=":" label-width="140px">
        <el-form-item label="随访计划名称" prop="name">
          <el-input v-model="planDetailData.name" maxlength="20" style="width: 30%" size="small" clearable></el-input>
        </el-form-item>
        <el-form-item label="随访居民" required>
          <div class="select-patients">
            <el-button plain icon="el-icon-plus" size="small" @click="selectPatientHandler">{{planDetailData.patientIdList ? '继续添加' : '选择居民'}}</el-button><br>
            <el-button type="text" class="mt10" size="small" @click="seeSelectedHandler" v-if="planDetailData.patientIdList">已选{{hasSelectedList.length}}人<i class="el-icon-arrow-right"></i></el-button>
          </div>
        </el-form-item>
        <el-form-item label="随访模板" prop="resourceName">
          {{planDetailData.resourceName}}
        </el-form-item>
        <el-form-item label="随访开始时间" prop="timeStr">
          {{planDetailData.timeStr}} <el-button class="btn-text" type="text" @click="goToFollowTime" size="small">查看全部></el-button>
        </el-form-item>
        <el-form-item label="备注">
          <el-select
            v-model="planDetailData.remarksStatus"
            placeholder="请选择随访种类"
            size="small"
            :popper-append-to-body="false"
            clearable>
            <el-option
              v-for="item in remarkOption"
              :key="item.no"
              :label="item.value"
              :value="item.no">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="edit-plan-content">
        <set-time-node
          :isStandedTemplate="isStandedTemplate"
          :standedTimeNodeList="setTimeNodeList"
          :patientIdList="planDetailData.patientIdList"
          :checkForm="checkForm"
          :planId="planId"
          @addListenSave="addListenSave"
        />
      </div>
    </div>
    <select-patient
      :isShowSelectPatient="isShowSelectPatient"
      :patientIdList="planDetailData.patientIdList"
      :oldPatientIdList="selectResidentIdList"
      @closeSelectPatient="closeSelectPatient"
      @sureSelectPatient="sureSelectPatient(arguments)">
    </select-patient>
    <has-selected-patient
      v-if="isShowSelectedDialog"
      :hasSelectedList="hasSelectedList"
      @closeSelectedDialog="closeSelectedDialog"
      @continueAdd="continueAdd" />
    <follow-time :showThisPage="showFollowTime" :nodeTimeList="nodeTimeList" @closeFollowTime="closeFollowTime"></follow-time>
    <add-patient-time
      :showThisPage="showAddPatientTime"
      :addPatientData="addPatientData"
      @sendJoinTime="sendJoinTime"
      @closeAddPatientTime="closeAddPatientTime"></add-patient-time>
  </div>
</template>

<script>
  import SelectPatient from '@/views/followup/plan-manage/dialog/select-patient';
  import HasSelectedPatient from '@/views/followup/plan-manage/dialog/has-selected-patient';
  import SetTimeNode from '@/views/followup/plan-manage/dialog/set-time-node';

  import FollowTime from '@/views/followup/plan-manage/dialog/follow-time';
  import {createFollowPlan} from '@/utils/followup/followapis'
  //添加居民选择随访时间
  import addPatientTime from '@/views/followup/plan-manage/dialog/add-patient-time';

  import { mapState, mapActions } from 'vuex'
  import * as commonUtil from '../../../utils/utils'

  export default {
    name: "plan-modify",
    components: {
      SelectPatient,
      HasSelectedPatient,
      SetTimeNode,
      FollowTime,
      addPatientTime
    },
    data() {
      return {
        setTimeNodeList: [],
        planDetailData: {},
        planId: '',
        isStandedTemplate: false, // 是否是固定的随访模板
        standedTimeNodeList: [], // 如果是国定随访模板，获取固定数据后不可更改，只读
        checkForm: false,
        patientIdList: [], //获取的病人列表
        hasSelectedList: [], //已选居民
        planModifyCrumb: [], //面包屑
        rules: {
          name: [{ required: true, message: '请输入随访计划名称', trigger: 'blur' }],
          followupTemplate: [{ required: true, message: '请选择随访模板', trigger: 'change' }],
          startTime: [{ required: true, message: '请选择随访开始时间', trigger: 'change' }],
        },
        templateOptions: [
          {
            value: '0',
            label: '随访模板一'
          }, {
            value: '1',
            label: '随访模板二'
          }, {
            value: '2',
            label: '随访模板三'
          }
        ],
        isShowSelectPatient: false, //显示居民选择框
        isShowSelectedDialog: false, //显示已选居民
        nodeListModify: [], //修改node列表
        showFollowTime: false,  //是否展示全部时间
        showAddPatientTime: false,//是否展示添加居民选择时间
        addPatientData: {}, //选择时间数据

        oldSelect:[],
        selectResidentIdList: [], //oldID
        newHasSelectedList: [],
        initResidentList: [], //重置需要的居民列表
        initResidentIdList: [],  //重置需要的id
      }
    },
    created() {
      this.planId = String(this.$route.query.planId)
      this.getPlanDetail(this.$route.query.planId); //获取计划详情
      this.getRemarkOption()
      this.getNodeTimeList(this.$route.query.planId); // 获取随访时间列表

      let planModifyCrumbList = sessionStorage.getItem('planModifyCrumb');
      this.planModifyCrumb = JSON.parse(planModifyCrumbList);
    },
    // 挂载到Dom完成时
    mounted: function() {
        commonUtil.resizeHeight()
    },
    computed: {
      ...mapState('planManage', {
        planDetail: state => state.planDetail,
        nodeTimeList: state => state.nodeTimeList,
        residentList: state => state.residentList,
        remarkOption: state => state.remarkOption,
        selectResidentList: state => state.selectResidentList
      })
    },
    methods: {
      ...mapActions('planManage', [
        'getPlanDetail',
        'getNodeTimeList',
        'getResidentList',
        'getRemarkOption',
        'getTimeNodeList',
        'setFollowPlan',
        'getSelectResident'
      ]),
      selectPatientHandler() {
        this.isShowSelectPatient = true;
      },
      closeSelectPatient(val) {
        this.isShowSelectPatient = val;
      },
      seeSelectedHandler() {
        this.isShowSelectedDialog = true;
      },
      closeSelectedDialog(val) {
        this.isShowSelectedDialog = val;
      },
      sureSelectPatient() {
        let getArguments = arguments[0];
        this.isShowSelectPatient = getArguments[0];
        const newAddPatientList = getArguments[1]; // 新选中的人
        let showNames = [];
        const newIds = [];
        newAddPatientList.forEach(item => {
          showNames.push(item.nickname)
          newIds.push(item.patientId)
        })
        this.newHasSelectedList = JSON.parse(JSON.stringify(this.initResidentList));
        this.newHasSelectedList = this.newHasSelectedList.concat(newAddPatientList);
        if(this.newHasSelectedList.length > this.hasSelectedList.length) {
          this.showAddPatientTime = true;
          if(showNames.length>5) {
            const le = showNames.length
            showNames = showNames.slice(0,5)
            showNames = `${showNames.join('、')}等${le}人`
          } else {
            showNames = showNames.join('、')
          }
          this.addPatientData = {
            id: this.$route.query.planId,
            addPatients: true,
            patientNames: showNames,
          }
        } else {
          this.hasSelectedList = JSON.parse(JSON.stringify(this.newHasSelectedList));
          this.planDetailData.patientIdList = JSON.parse(JSON.stringify(this.initResidentIdList));
          const _this = this;
          newAddPatientList.forEach(item => {
            _this.planDetailData.patientIdList.push(item.patientId)
          })
        }
      },
      continueAdd(val) {
        this.isShowSelectedDialog = val;
        this.isShowSelectPatient = true;
      },
      cancelEdit() {
        this.$confirm('是否放弃本次修改?', '', {
          confirmButtonText: '继续修改',
          cancelButtonText: '确定放弃',
          type: 'warning'
        }).then(() => {
          //  关闭弹层，继续创建
        }).catch(() => {
          //  确定放弃，跳出当前编辑页面
          this.$router.back(-1)
        });
      },
      saveModify() {
        // 点击保存，先进行校验，表单字段是否通过验证
        this.checkForm = true
      },
      // 监听保存校验结果
      addListenSave(val){
//        console.log('监听保存校验结果',val)
        this.checkForm = false
        if(val.status){
          this.$confirm('是否确认保存修改内容?', '', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 点击保存，先进行校验，表单字段是否通过验证
            //  关闭弹层，继续创建
            this.planDetailData.fPlanTimeReqList = val.setTimeNodeList
//            this.planDetailData.joinTime = new Date();
//            this.planDetailData.joinTime = (new Date(this.planDetailData.joinTime)).getTime()
//            console.log(this.planDetailData.joinTime)
//            console.log('修改计划前的数据===>>>',this.planDetailData)
            createFollowPlan(this.planDetailData).then(res=>{
              if(res.code=='000000'){
                //  各种校验通过后，提交编辑内容，toast提示
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                setTimeout(()=>{
                  this.$router.push({
                    path: '/followup/plan-manage/plan-list'
                  })
                },2000)
              }else{
                this.$message({
                  message: '创建失败,' + res.message,
                  type: 'error'
                });
              }
            })
          })
        }else{
          this.$message({
            message: val.message,
            type: 'error'
          });
        }
      },
      goToFollowTime() {
        this.showFollowTime = true
      },
      closeFollowTime(isShow) {
        this.showFollowTime = isShow
      },
      closeAddPatientTime(isShow) {
        this.showAddPatientTime = isShow
      },
      sendJoinTime(joinData) {
        const _this = this;
        if(joinData) {
          _this.hasSelectedList = [];
          _this.planDetailData.patientIdList = [];
          _this.newHasSelectedList.forEach(item => {
            _this.hasSelectedList.push(item)
            _this.planDetailData.patientIdList.push(item.patientId)
          })
          this.planDetailData.joinTime = joinData;
        } else {

        }
      },
    },
    watch: {
      planDetail(val) {
        this.planDetailData = val;
        this.setTimeNodeList = val.fPlanTimeReqList
        if(this.planDetailData.resourceId){
          this.isStandedTemplate = true
        }else{
          this.isStandedTemplate = false
        }
      },
      selectResidentList(val) {
        const _this = this
        _this.planDetailData.patientIdList = []
        let people = {}
        if(val) {
          val.forEach(function (item, index) {
            people = {
              nickname: item.patientName,
              age: item.age,
              id: item.idNo,
              mobilePhone: item.mobilePhone,
              labelId: item.labelName,
              patientId: item.patientId
            };
            _this.hasSelectedList.push(people);
            _this.planDetailData.patientIdList.push(item.patientId)
            _this.selectResidentIdList.push(item.patientId)
            _this.initResidentList.push(people);
            _this.initResidentIdList.push(item.patientId);
          })
          _this.newHasSelectedList = JSON.parse(JSON.stringify(_this.initResidentIdList));
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../../../style/followup/followup-common';
  @import '../../../style/followup/element-reset.css';
  .bread-crumb {
    position: fixed;
    left: 255px;
    top: 64px;
    width: 100%;
    background: #fff;
    height: 61px;
    padding: 20px 20px 30px;
    z-index: 99;
    border-top: 3px solid #F0F2F5;
    .el-breadcrumb__inner {
      font-size: 14px;
    }
    a:hover {
      color: #449284;
    }
  }
  .header{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 20px;
    border-bottom: $borderBottomStyle;
    margin-bottom: 30px;
  }
  .edit-plan-content{
    padding: 30px 0;

    .add-time-content{
      padding-top: 20px;
      .time-line-scroll{
        width: 100%;
        height: 50px;
        box-sizing: border-box;
        background-color: #F0F2F5;
        padding: 8px 10px;
        /*display: flex;*/
        /*align-items: center;*/
        overflow-x: scroll;
        overflow-y: hidden;
        white-space: nowrap;
        position: relative;
        cursor: pointer;
        &::-webkit-scrollbar{
          height: 6px;
        }
        &::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
          border-radius: 10px;
          -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
          background: rgba(0,0,0,0.1);
        }
        span{
          display: inline-block;
          background-color: #449284;
          border-radius: 20px;
          height: 28px;
          line-height: 28px;
          padding: 0 8px;
          color: #ffffff;
          font-size: 12px;
          width: 95px;
        }
      }
      .form-div{
        padding-top: 30px;
      }
    }


  }
</style>
