<template>
  <!-- dutyLogApproval  审批按钮权限 -->
  <div class="edit-add-detail">
    <div
      v-loading="formLoading"
      class="form-content"
      element-loading-background="rgba(10 ,38 ,61, 0.95)"
      element-loading-text="数据加载中..."
    >
      <el-form
        ref="addEditForm"
        :model="addEditForm"
        :rules="addEditRules"
        label-position="left"
        label-suffix="："
        label-width="120px"
      >
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">值班日志</div>
          </div>
        </div>                                                                                                                                                                                                                                                                              
        <div class="form-wrapper">
          <div class="title">
            <div>运行监测调度中心</div>
            <div>值 班 记 录</div>
          </div>
          <el-descriptions :column="3" border :labelStyle="{width: '140px'}">
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star">*</span>所属路段
              </template>
              <el-form-item prop="roadInfos">
                <el-select
                  v-model="addEditForm.roadInfos"
                  multiple
                  placeholder="请选择所属路段"
                >
                  <el-option
                    v-for="item in roadOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <span class="required-star">*</span>班次
              </template>
              <el-form-item prop="shiftName">
                <el-select
                  v-model="addEditForm.shiftName"
                  style="width: 100%"
                  placeholder="请选择班次"
                  clearable
                >
                  <el-option
                    v-for="item in getDictionaryByCode('pbbc')"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :span="2">
              <template slot="label">
                <span class="required-star">*</span>工作时间
              </template>
              <el-form-item prop="dateRange">
                <el-date-picker
                  range-separator="至"
                  start-placeholder="工作开始时间"
                  end-placeholder="工作结束时间"
                  v-model="addEditForm.dateRange"
                  type="datetimerange"
                  format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH:mm:00"
                  :default-time="['00:00:00', '23:59:59']"
                ></el-date-picker>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star">*</span>值班人员
              </template>
              <el-form-item prop="dutyPersonnel">
                <el-input
                  type="textarea"
                  rows="2"
                  v-model="addEditForm.dutyPersonnel"
                  placeholder="请输入值班人员"
                  @blur="trimField('dutyPersonnel')"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star text-row">* <span class="text-row-color">值班记录</span></span>
              </template>
              <el-form-item prop="dutySituation">
                <el-input
                  type="textarea"
                  rows="12"
                  placeholder="请输入当班情况记录"
                  v-model="addEditForm.dutySituation"
                  @blur="trimField('dutySituation')"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions
            :column="6"
            border
            class="el-descriptions-table"
            direction="vertical"
          >
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              交通事故
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="trafficAccidentCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.trafficAccidentCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="trafficAccidentDetail">
                <el-input
                  v-model="addEditForm.trafficAccidentDetail"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              人员伤亡
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="casualtyCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.casualtyCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="casualtyDetail">
                <el-input v-model="addEditForm.casualtyDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>

            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              管制情况
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="controlSituationCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.controlSituationCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="controlSituationDetail">
                <el-input
                  v-model="addEditForm.controlSituationDetail"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              重大事件记录
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="majorEventCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.majorEventCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="majorEventDetail">
                <el-input v-model="addEditForm.majorEventDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>

            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              拥堵情况
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="congestionCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.congestionCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="congestionDetail">
                <el-input v-model="addEditForm.congestionDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              设备报修
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="equipmentRepairCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.equipmentRepairCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="equipmentRepairDetail">
                <el-input
                  v-model="addEditForm.equipmentRepairDetail"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>

            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              投诉记录
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="complaintCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.complaintCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="complaintDetail">
                <el-input v-model="addEditForm.complaintDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              清障救援
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="rescueCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.rescueCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="rescueDetail">
                <el-input v-model="addEditForm.rescueDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              外单位来访
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="visitCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.visitCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="visitDetail">
                <el-input v-model="addEditForm.visitDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>

            <el-descriptions-item label="事项" :labelStyle="{width: '140px'}">
              来电询问
            </el-descriptions-item>
            <el-descriptions-item label="数量" :labelStyle="{width: '120px'}">
              <el-form-item prop="inquiryCount">
                <el-input-number
                  :controls="false"
                  v-model="addEditForm.inquiryCount"
                ></el-input-number>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="详情">
              <el-form-item prop="inquiryDetail">
                <el-input v-model="addEditForm.inquiryDetail"></el-input>
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions border :labelStyle="{width: '140px'}">
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star text-row">* <span class="text-row-color">交接情况</span></span>
              </template>
              <el-form-item prop="handoverSituation">
                <el-input
                  type="textarea"
                  rows="6"
                  placeholder="请输入交接情况"
                  v-model="addEditForm.handoverSituation"
                  @blur="trimField('handoverSituation')"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star text-row">* <span class="text-row-color">设施设备</span></span>
              </template>
              <el-form-item prop="facilityStatus">
                <el-input
                  type="textarea"
                  rows="6"
                  placeholder="请输入设施设备情况"
                  v-model="addEditForm.facilityStatus"
                  @blur="trimField('facilityStatus')"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :span="3">
              <template slot="label">
                <span class="required-star">*</span>接班人员
              </template>
              <el-form-item prop="nextShiftPersonnel">
                <el-input
                  type="textarea"
                  rows="2"
                  placeholder="请输入接班人员"
                  v-model="addEditForm.nextShiftPersonnel"
                  @blur="trimField('nextShiftPersonnel')"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item
              :span="3"
              v-if="BtnAuth('dutyLogApproval') && id"
            >
              <template slot="label">
                <span class="required-star">*</span>管理员意见
              </template>
              <el-form-item prop="adminComment">
                <el-input
                  type="textarea"
                  rows="2"
                  v-model="addEditForm.adminComment"
                  placeholder="请输入管理员意见"
                  @blur="trimField('adminComment')"
                ></el-input>
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-form>
    </div>

    <div slot="footer" class="footer">
      <el-button
        v-if="BtnAuth('dutyLogApproval') && id"
        :disabled="formLoading"
        :loading="saveLoading"
        type="warning"
        @click="handleSave('audit')"
      >
        审核并保存
      </el-button>
      <el-button
        :disabled="formLoading"
        :loading="saveLoading"
        type="primary"
        @click="handleSave"
      >
        {{ $t('domestic.save') }}
      </el-button>
      <el-button @click="changePage('TablePage')">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>

    <el-backtop :visibility-height="10" target=".el-form">
      <div class="top-box">UP</div>
    </el-backtop>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import moment from 'moment'
import 'moment-duration-format'
import { getDictionaryByCode} from '@/utils/dictionary'
import {
  tableAdd,
  tableEdit,
  tableDetail,
  getDutyPerson,
  auditDutyRecord,
  getReplacePerson
} from '@/api/patrolAndRescue/commandDispatch/reportManagement/dutyRecords.js'
import {roadData} from '@/api/patrolAndRescue/roadDamageComp/roadDamageRegister'
import utils from '@/utils/utils.js'

export default {
  name: 'EditAddPage',
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  data() {
    return {
      dutyLogApproval: '',
      addEditForm: {
        roadInfos: [],
        shiftName: '',
        dateRange: [
          moment()
            .subtract(1, 'day')
            .hour(9)
            .minute(0)
            .second(0)
            .format('YYYY-MM-DD HH:mm:ss'),
          moment()
            .subtract(1, 'day')
            .hour(18)
            .minute(0)
            .second(0)
            .format('YYYY-MM-DD HH:mm:ss')
        ],
        startTime: '',
        endTime: '',
        dutyPersonnel: '',
        dutySituation: '',
        handoverSituation: '',
        facilityStatus: '',
        nextShiftPersonnel: '',
        trafficAccidentCount: 0,
        trafficAccidentDetail: '详见突发事件记录',
        casualtyCount: 0,
        casualtyDetail: '详见突发事件记录',
        controlSituationCount: 0,
        controlSituationDetail: '详见值班日志',
        majorEventCount: 0,
        majorEventDetail: '详见重大事件记录',
        congestionCount: 0,
        congestionDetail: '详见值班日志',
        equipmentRepairCount: 0,
        equipmentRepairDetail: '详见设备报修记录',
        complaintCount: 0,
        complaintDetail: '详见投诉记录',
        rescueCount: 0,
        rescueDetail: '详见清障救援记录',
        visitCount: 0,
        visitDetail: '详见外单位来访记录',
        inquiryCount: 0,
        inquiryDetail: '详见来电记录',
        adminComment: ''
      },
      addEditRules: {
        roadInfos: [
          {required: true, message: '路段不能为空', trigger: 'change'}
        ],
        shiftName: [
          {required: true, message: '班次不能为空', trigger: 'change'}
        ],
        dateRange: [
          {required: true, message: '日期不能为空', trigger: 'change'}
        ],
        dutyPersonnel: [
          {required: true, message: '值班人员不能为空', trigger: 'change'}
        ],
        dutySituation: [
          {required: true, message: '值班情况不能为空', trigger: 'change'}
        ],
        handoverSituation: [
          {required: true, message: '交接情况不能为空', trigger: 'change'}
        ],
        facilityStatus: [
          {required: true, message: '设施设备不能为空', trigger: 'change'}
        ],
        nextShiftPersonnel: [
          {required: true, message: '接班人员不能为空', trigger: 'change'}
        ],
        adminComment: [
          {required: true, message: '管理员意见', trigger: 'change'}
        ]
      },
      saveLoading: false, // 上传loading
      formLoading: false, // 上传loading
      roadOptions: [], // 路段数据
      id: '', // id标识符
      pubSub: null
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  created() {},
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      this.getRoadData()
      // 新增或修改
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      }else{
      this.getDutyPersonData()
      this.getReplacePersonData()
        this.addEditForm.shiftName = this.getDictionaryByCode('pbbc')[0].value || ''
      }
    })
  },
  methods: {
        // 删除
    saveConfirm(type='save') {
      this.$confirm(`确定${type === 'audit'? '审核并保存' : '保存'}值班日志吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.saveLoading = true
          let {
            dateRange = [],
            roadInfos = [],
            ...addEditForm
          } = this.addEditForm
          const API = this.id && type==='audit' ? auditDutyRecord : this.id ? tableEdit : tableAdd

          const roadInfosAll = this.roadOptions.filter(item =>
            roadInfos.includes(item.id)
          )
          try {
            let {state, message} = await API({
              ...addEditForm,
              roadInfos: roadInfosAll,
              startTime: dateRange[0],
              endTime: dateRange[1]
            })

            if (state) {
              message = this.id && type==='audit' ?  '审核并保存' : this.id ? '修改' : '新增'
              this.$message.success(`值班日志${message}成功`)
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        })
        .catch(_ => _)
    },
    trimField(fieldName) {
      if (this.addEditForm[fieldName]) {
        this.addEditForm[fieldName] = this.addEditForm[fieldName].trim()
      }
    },
    BtnAuth(btnCode) {
      return utils.BtnAuth(btnCode)
    },
    async getDutyPersonData() {
      const res = await getDutyPerson()
      const dutyPerson = res.reduce((acc, cur) => {
        return acc += cur.userName + ','
      }, '')
      this.addEditForm.dutyPersonnel = dutyPerson.slice(0, -1)
    },
    async getReplacePersonData() {
      const res = await getReplacePerson()
      const dutyPerson = res.reduce((acc, cur) => {
        return acc += cur.userName + ','
      }, '')
      this.addEditForm.nextShiftPersonnel = dutyPerson.slice(0, -1)
    },
    async getRoadData() {
      try {
        const {rows = []} = await roadData({pageBean: {pageSize: -1}})
        this.roadOptions = rows
        if(!this.id){
          this.addEditForm.roadInfos = rows[0] && [rows[0].id || '']
        }
      } catch (e) {
        console.log(e)
      }
    },

    // 获取详情
    async getDetail(id) {
      this.formLoading = true
      try {
        let {
          startTime = '',
          endTime = '',
          roadInfos = [],
          ...addEditForm
        } = await tableDetail(id)
        const roadInfosId = roadInfos.map(i => i.id)
        this.addEditForm = {
          ...addEditForm,
          dateRange: [startTime, endTime],
          startTime,
          endTime,
          roadInfos: roadInfosId
        }
      } finally {
        this.formLoading = false
      }
    },

    // 打开页面执行
    openPage() {},

    // 关闭页面执行
    closePage() {
      const {addEditRules, pubSub} = this

      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        addEditRules,
        pubSub
      })

      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },
    // 保存
    handleSave(type = 'save') {
      // 保存原始的adminComment验证规则
      const originalAdminCommentRule = this.addEditRules.adminComment
      
      // 根据操作类型动态设置adminComment的验证规则
      if (type === 'audit') {
        // 审核操作：adminComment为必填
        this.addEditRules.adminComment = [
          {required: true, message: '管理员意见', trigger: 'change'}
        ]
      } else {
        // 保存操作：adminComment为非必填
        this.addEditRules.adminComment = []
      }
      
      this.$refs.addEditForm.validate(async (valid, object) => {
        // 验证完成后恢复原始的验证规则
        this.addEditRules.adminComment = originalAdminCommentRule
        
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveConfirm(type)
        }
      })
    },

    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      this[dialogName + 'Dialog'] = true
    },

    // 改变页面
    changePage(pageName = '', type = '') {
      if (!pageName) return
      this.$emit('changePage', pageName, _ => {
        PubSub.publish(pageName, {type})
      })
    },
    getDictionaryByCode
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables';
::v-deep .el-form-item__content {
  margin-left: 0 !important;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
::v-deep
  .el-descriptions
  .el-descriptions__body
  .el-descriptions-row
  .el-descriptions-item__cell.el-descriptions-item__label {
  width: auto;
  text-align: center;
}
::v-deep
  .el-descriptions
  .el-descriptions__body
  .el-descriptions-row
  .el-descriptions-item__cell.el-descriptions-item__content {
  text-align: center;
}
.required-star {
  color: #f56c6c;
  padding-right: 4px;
}

.edit-add-detail {
  .form-content .el-form {
    display: flex;
    flex-direction: column;
    overflow-y: hidden !important;
  }

  .form-wrapper {
    flex: 1;
    overflow-y: auto;
    width: 1220px;
    margin: 0 auto 10px;
    padding: 0 100px;
    .title {
      margin: 10px 0;
      > div {
        font-size: 24px;
        text-align: center;
      }
    }
  }
}
::v-deep .el-input-number {
  width: 100px;
}
.text-row{
  writing-mode: vertical-rl;
  letter-spacing: 12px;
}
.text-row-color{
  font-size: 15px;
  font-family: PingFang SC-Medium, PingFang SC, serif;
  color: #f0f0f0;
}
</style>
