<template>
  <div class="resident-list">
    <bread-crumb
      :curmbFirst="curmbFirst"
      :curmbSecond="curmbSecond"
      :curmbThird="curmbThird"
      :jumPathThird="jumPathThird"
    >
    </bread-crumb>
    <div class="new-plan-content f-main-content screenSet">
      <div class="header">
        <div class="title">
          <span :class="{ 'active-class': activeTab === 'second' }"
            >①基本信息</span
          >
          <i class="el-icon-arrow-right" style="color: #c0c4cc"></i>
          <span :class="{ 'active-class': activeTab === 'first' }"
            >②履约时间节点</span
          >
        </div>
        <div class="plan-btns-group" v-if="activeTab === 'first'">
          <el-button class="button-white" size="small" plain @click="cancelEdit"
            >取 消</el-button
          >
          <el-button type="primary" size="small" @click="nextClick('baseInfo')"
            >下一步</el-button
          >
        </div>
        <div class="plan-btns-group" v-if="activeTab === 'second'">
          <el-button class="button-white" size="small" plain @click="preClick"
            >上一步</el-button
          >
          <el-button type="primary" size="small" @click="saveEdit"
            >保 存</el-button
          >
        </div>
      </div>

      <div class="edit-plan-content" v-if="activeTab === 'first'">
        <el-form
          ref="baseInfo"
          :model="baseInfo"
          :rules="rules"
          label-suffix=":"
          label-width="140px"
          :inline-message="true"
          size="small"
        >
          <el-form-item label="履约计划名称" prop="name">
            <el-input
              v-model:value="baseInfo.name"
              maxlength="20"
              style="width: 30%"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="履约居民" required prop="hasSelectedNum">
            <div style="display: flex">
              <div>
                <el-button
                  plain
                  icon="el-icon-plus"
                  :style="noChoice ? 'border:1px solid red;' : ''"
                  @click="selectPatientHandler"
                  >{{
                    baseInfo.hasSelectedNum ? '继续添加' : '选择居民'
                  }}</el-button
                ><br />
                <el-button
                  type="text"
                  class="mt10"
                  @click="seeSelectedHandler"
                  v-if="baseInfo.hasSelectedNum"
                  >已选{{ baseInfo.hasSelectedNum }}人<i
                    class="el-icon-arrow-right"
                  ></i
                ></el-button>
              </div>
              <p class="err-tips" v-if="noChoice">请添加履约居民</p>
            </div>
          </el-form-item>
          <el-form-item label="履约模板" prop="resourceId">
            <el-select
              v-model:value="baseInfo.resourceId"
              placeholder="请选择履约模板"
              clearable
            >
              <el-option
                v-for="item in templateOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <p class="tips">履约计划创建成功后，模板不可更换，请谨慎选择。</p>
          <el-form-item label="履约开始时间" prop="time">
            <el-date-picker
              v-model:value="baseInfo.time"
              type="date"
              ref="beginDate"
              placeholder="请选择履约开始时间"
              :picker-options="pickerOptions"
              value-format="timestamp"
              clearable
              @blur="handleDateInputConfirm"
              style="width: 380px"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注">
            <el-select
              v-model:value="baseInfo.remarksStatus"
              placeholder="请选择履约种类"
              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>

      <div class="edit-plan-content" v-show="activeTab === 'second'">
        <set-time-node
          :resourceId="resourceId"
          :standedTimeNodeList="standedTimeNodeList"
          :isStandedTemplate="isStandedTemplate"
          :patientIdList="baseInfo.patientIdList"
          :checkForm="checkForm"
          @addListenSave="addListenSave"
        />
      </div>
    </div>

    <select-patient
      :isShowSelectPatient="isShowSelectPatient"
      :patientIdList="baseInfo.patientIdList"
      @closeSelectPatient="closeSelectPatient"
      @sureSelectPatient="sureSelectPatient(arguments)"
      :selectPatientType="selectPatientType"
    />
    <has-selected-patient
      v-if="isShowSelectedDialog"
      :hasSelectedList="hasSelectedList"
      @closeSelectedDialog="closeSelectedDialog"
      @continueAdd="continueAdd"
    />
  </div>
</template>

<script>
import BreadCrumb from '@/components/breadcrumb'
// import SelectPatient from '@/views/followup/plan-manage/dialog/select-patient';
import SelectPatient from '@/views/patients/labels-manage/dialog/select-patitents'
import HasSelectedPatient from '@/views/followup/plan-manage/dialog/has-selected-patient'
import SetTimeNode from '@/views/followup/plan-manage/dialog/set-time-node'
import {
  createFollowPlan,
  getFollowupTableTemplate,
} from '@/utils/followup/followapis'

import { mapState, mapActions } from 'vuex'
export default {
  name: 'addNewPlan',
  components: {
    BreadCrumb,
    SelectPatient,
    HasSelectedPatient,
    SetTimeNode,
  },
  data() {
    return {
      setTimeNodeList: [], //重写后的setTimeNodeList
      isStandedTemplate: false, // 是否是固定的履约模板
      standedTimeNodeList: [], // 如果是国定履约模板，获取固定数据后不可更改，只读
      checkForm: false,
      /*面包屑配置*/
      curmbFirst: '履约管理',
      curmbSecond: '计划管理',
      curmbThird: '新建履约计划',
      jumPathThird: '/followUp/plan-manage',
      activeTab: 'first',
      resourceId: '', //当前选择的履约模板id
      noName: false,
      noResourceId: false,
      noTime: false,
      noChoice: false,
      baseInfo: {
        name: '', //履约计划名称
        patientIdList: [], //履约居民列表
        resourceId: '', //履约模板ID
        time: '', //履约开始时间
        remarksStatus: '',
        fPlanTimeReqList: [], //时间节点列表
        hasSelectedNum: 0,
      },
      isShowSelectPatient: false,
      isShowSelectedDialog: false,
      selectPatientType: 1,
      hasSelectedList: [],
      rules: {
        name: [
          { required: true, message: '请输入履约计划名称', trigger: 'blur' },
        ],
        hasSelectedNum: [
          { required: true, message: '请添加履约居民', trigger: 'change' },
        ],
        resourceId: [
          { required: true, message: '请选择履约模板', trigger: 'change' },
        ],
        time: [
          { required: true, message: '请选择履约开始时间', trigger: 'change' },
        ],
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        },
      },
    }
  },
  created() {
    // 获取备注
    this.getRemarkOption()
    // 获取履约计划模板列表
    this.getFollowupTemplate()
  },
  computed: {
    ...mapState('planManage', {
      remarkOption: (state) => state.remarkOption,
      templateOptions: (state) => state.templateOptions,
    }),
  },
  methods: {
    ...mapActions('planManage', [
      'getTimeNodeList',
      'getRemarkOption',
      'getFollowupTemplate',
    ]),

    // 点击保存
    saveEdit() {
      // 点击保存，先进行校验，表单字段是否通过验证
      this.checkForm = true
    },
    handleDateInputConfirm(e) {
      if (!this.baseInfo.time) {
        this.$refs.beginDate.picker.date = new Date()
      }
    },
    // 监听保存校验结果
    addListenSave(val) {
      //         console.log('监听保存校验结果',val)
      this.checkForm = false
      if (val.status) {
        this.baseInfo.fPlanTimeReqList = val.setTimeNodeList
        //           this.baseInfo.time = (new Date(this.baseInfo.time).getTime())
        //           console.log(this.baseInfo.time)
        // 提交
        createFollowPlan(this.baseInfo).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',
        })
      }
    },
    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 selectPatients = getArguments[1] // 每次选中获取的人
      this.hasSelectedList = selectPatients
      //        console.log('呵呵呵呵',arguments)
      this.baseInfo.patientIdList = []
      selectPatients.forEach((item) => {
        this.baseInfo.patientIdList.push(item.patientId)
      })
      this.baseInfo.hasSelectedNum = this.hasSelectedList.length
      if (this.baseInfo.hasSelectedNum > 0) {
        this.noChoice = false
      }
    },
    continueAdd(val) {
      this.isShowSelectedDialog = val
      this.isShowSelectPatient = true
    },
    cancelEdit() {
      this.$confirm('是否放弃本次创建，放弃后数据不能被保存', '', {
        confirmButtonText: '继续创建',
        cancelButtonText: '确定放弃',
        type: 'warning',
      })
        .then(() => {
          //  关闭弹层，继续创建
        })
        .catch(() => {
          //  确定放弃，跳出当前编辑页面
          this.$router.push({ path: '/followup/plan-manage/plan-list' })
        })
    },
    nextClick(formName) {
      //为方便调试，不做校验
      //         this.activeTab = 'second';
      this.$refs[formName].validate((valid) => {
        //用作校验
        if (!this.baseInfo.hasSelectedNum) {
          this.noChoice = true
          return
        } else {
          this.noChoice = false
        }
        if (valid) {
          //            console.log('当前选择的履约模板id为',this.baseInfo.resourceId)
          this.resourceId = String(this.baseInfo.resourceId)
          //            console.log( this.baseInfo.resourceId)
          if (this.baseInfo.resourceId) {
            getFollowupTableTemplate(this.baseInfo.resourceId).then((res) => {
              this.isStandedTemplate = true
              this.standedTimeNodeList = res.data
              this.activeTab = 'second'
            })
          } else {
            this.isStandedTemplate = false
            this.standedTimeNodeList = []
            this.activeTab = 'second'
          }
        } else {
          return false
        }
      })
    },
    preClick() {
      this.activeTab = 'first'
    },
  },
}
</script>

<style lang="scss" scoped>
@import '../../../style/followup/followup-common';
@import '../../../style/followup/element-reset.css';
.new-plan-content {
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 20px;
    border-bottom: $borderBottomStyle;
    .title {
      .active-class {
        color: #9b9997;
      }
    }
  }
  .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;
      }
    }
  }
  .err-tips {
    color: #f56c6c;
    font-size: 12px;
    margin-left: 10px;
  }
  .tips {
    font-size: 12px;
    color: #9b9997;
    padding-left: 140px;
    margin-top: -10px;
    padding-bottom: 15px;
  }
  .el-message-box__content {
    padding: 20px 15px;
  }
}
.mt10 {
  margin-top: 10px;
}
.ml20 {
  margin-left: 20px;
}
</style>
