<template>
  <div class="edit-add-detail">
    <div class="form-content">
      <el-form ref="addEditForm" :model="addEditForm" :rules="addEditRules" class="edit-add-form" label-position="left"
               label-width="140px">
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">基础信息</div>
          </div>
        </div>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="投诉路段" prop="roadName">
              <el-input v-model="addEditForm.roadName" clearable disabled placeholder="请输入投诉路段"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="24">
            <el-form-item label="投诉来源" prop="complaintSource">
              <el-radio-group v-model="addEditForm.complaintSource">
                <el-radio v-for="(item, index) in getDictionaryByCode(
                    'yxjc-tsly'
                  )" :key="index" :label="Number(item.value)" :value="Number(item.value)" border>
                  {{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left:80px">
          <el-col :span="24">
            <el-form-item label="具体来源" prop="specificSource">
              <el-radio-group v-model="addEditForm.specificSource" size="medium">
                <el-radio v-for="(item, index) in getDictionaryByCode(
                    'yxjc-jtly'
                  )" :key="index" :label="Number(item.value)" :value="Number(item.value)">{{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="投诉时间" prop="complaintTime">
              <el-date-picker
                v-model="addEditForm.complaintTime"
                default-time="12:00:00"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                style="width: 100%"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">投诉信息</div>
          </div>
        </div>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="投诉人姓名" prop="complainantName">
              <el-input v-model="addEditForm.complainantName" clearable placeholder="请输入投诉人姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="投诉人联系方式" prop="complainantContactInformation">
              <el-input v-model="addEditForm.complainantContactInformation" clearable placeholder="请输入投诉人联系方式"
                        type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="接诉人姓名" prop="respondent">
              <el-input v-model="addEditForm.respondent" clearable placeholder="请输入接诉人姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="接诉时间" prop="responseTime">
              <el-date-picker
                v-model="addEditForm.responseTime"
                default-time="12:00:00"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                style="width: 100%"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="24">
            <el-form-item label="投诉类别" prop="complaintCategory">
              <el-radio-group v-model="addEditForm.complaintCategory" border size="medium">
                <el-radio v-for="(item, index) in getDictionaryByCode(
                    'yxjc-tslb'
                  )" :key="index" :label="Number(item.value)" :value="Number(item.value)" border>{{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="投诉对象" prop="complaintObject">
              <el-select v-model="addEditForm.complaintObject" clearable placeholder="投诉对象" style="width: 100%">
                <el-option v-for="(item, index) in getDictionaryByCode(
                    'yxjc-tsdx'
                  )" :key="index" :label="item.name" :value="Number(item.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="12">
            <el-form-item label="投诉事项" prop="complaintMatters">
              <el-input v-model="addEditForm.complaintMatters" :autosize="{ minRows: 2, maxRows: 4 }" clearable
                        placeholder="请输入投诉事项"
                        type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="24">
            <el-form-item label="投诉理由类型" prop="complaintReasonType">
              <el-radio-group v-model="addEditForm.complaintReasonType" border size="medium">
                <el-radio v-for="(item, index) in getDictionaryByCode(
                    'yxjc-tslylx'
                  )" :key="index" :label="Number(item.value)" :value="Number(item.value)" border>{{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="addEditForm.complaintReasonType===1" :gutter="24" style="margin-left: 80px">
          <el-col :span="12">
            <el-form-item label="具体投诉理由内容" prop="complaintReasonsContent">
              <el-input v-model="addEditForm.complaintReasonsContent" :autosize="{ minRows: 2, maxRows: 4 }" clearable
                        placeholder="请输入具体投诉理由内容"
                        type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="12">
            <el-form-item label="具体对象阐述" prop="specificObjectDescription">
              <el-input v-model="addEditForm.specificObjectDescription" :autosize="{ minRows: 2, maxRows: 4 }" clearable
                        placeholder="请输入具体对象阐述"
                        type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="12">
            <el-form-item label="备注" prop="notes">
              <el-input v-model="addEditForm.notes" :autosize="{ minRows: 2, maxRows: 4 }" clearable
                        placeholder="请输入备注"
                        type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="footer">
      <el-button :loading="saveLoading" type="primary" @click="handleSave">
        {{ $t('domestic.save') }}
      </el-button>
      <el-button @click="changePage('TablePage')">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import {tableAdd, tableDetail, tableEdit} from '@/api/patrolAndRescue/operationalMonitoring/complaintLedgerManagement'
import {getDictionaryByCode} from '@/utils/dictionary'
import {tableData as roadSectionInfoInter} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/roadSectionInfo'
import {mapState} from 'vuex'

export default {
  name: 'EditAddPage',
  components: {},
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  computed: {
    ...mapState({currentUser: (state) => state.user.currentUserDetail})
  },
  data() {
    return {
      id: '', // id标识符
      addEditForm: {
        roadId: '',
        roadName: '',
        roadCode: '',
        complaintTime: this.formatDate(new Date()),
        responseTime: this.formatDate(new Date()),
        complaintSource: 1,
        specificSource: 1,
        complaintCategory: 1,
        complaintObject: 1,
        complaintReasonType: 2,
        complainantName: '',
        complainantContactInformation: '',
        complaintMatters: '',
        complaintReasonsContent: '',
        specificObjectDescription: '',
        notes: '',
        respondent: ''
      },
      addEditRules: {
        roadName: [
          {required: true, message: '请输入投诉路段', trigger: 'blur'}
        ],
        complaintTime: [
          {required: true, message: '请选择投诉时间', trigger: 'change'}
        ],
        complaintSource: [
          {required: true, message: '请选择投诉来源', trigger: 'change'}
        ],
        specificSource: [
          {required: true, message: '请选择具体来源', trigger: 'change'}
        ],
        complaintCategory: [
          {required: true, message: '请选择投诉类别', trigger: 'change'}
        ],
        complaintObject: [
          {required: true, message: '请选择投诉对象', trigger: 'change'}
        ],
        complaintReasonType: [
          {required: true, message: '请选择投诉理由类型', trigger: 'change'}
        ],
        complaintMatters: [
          {required: true, message: '请输入投诉事项', trigger: 'blur'}
        ],
        complainantName: [
          {required: true, message: '请输入投诉人姓名', trigger: 'blur'}
        ],
        respondent: [
          {required: true, message: '请输入接诉人姓名', trigger: 'blur'}
        ],
        responseTime: [
          {required: true, message: '请选择接诉时间', trigger: 'change'}
        ],
        complainantContactInformation: [
          {required: true, message: '请输入投诉人联系方式', trigger: 'blur'},
          {pattern: /^1[3-9]\d{9}$/, message: '电话号码格式不正确', trigger: 'blur'}
        ],
        complaintReasonsContent: [
          {required: true, message: '请输入具体投诉理由内容', trigger: 'blur'}
        ]
      },
      saveLoading: false,
      pubSub: null,
      roadOptions: []
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  created() {
  },
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      this.addEditForm.respondent = this.currentUser.user.fullname
      // this.addEditForm.complainantContactInformation = this.currentUser.user.mobile
      // 第一层级不渲染 默认第一个
      if (data.roadName !== '' && data.path) {
        this.addEditForm.roadName = data?.roadName || ''
        this.addEditForm.roadId = data?.catalogId || ''
      }
      this.getRoadData()
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
    })
  },
  methods: {
    getDictionaryByCode,
    formatDate(date) {
      const pad = (num) => String(num).padStart(2, '0') // 补零函数
      const year = date.getFullYear()
      const month = pad(date.getMonth() + 1)
      const day = pad(date.getDate())
      const hours = pad(date.getHours())
      const minutes = pad(date.getMinutes())
      const seconds = pad(date.getSeconds())
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    //获取所在路段列表数据
    async getRoadData() {
      const {rows = []} = await roadSectionInfoInter({pageBean: {pageSize: -1}})
      this.roadOptions = rows.map(item => {
        item.roadName = item.name + ' ' + item.code
        return item
      })
      this.addEditForm.roadCode = this.roadOptions.filter(item => item.id === this.addEditForm.roadId)[0].code
    },
    // 打开页面执行
    openPage() {
    },
    // 关闭页面执行
    closePage() {
      const {roadOptions} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {pubSub: this.pubSub, roadOptions})
      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },
    // 获取详情
    async getDetail(id) {
      this.addEditForm = await tableDetail(id)
    },
    // 保存
    handleSave() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(`有${Object.keys(object).length}个字段未通过校验，请正确填写表单内容。`)
        } else {
          this.saveLoading = true
          const myInterFace = this.id ? tableEdit : tableAdd
          try {
            const response = await myInterFace({...this.addEditForm})
            const {state, message} = response
            if (state) {
              const action = this.id ? '编辑' : '新增'
              this.$message.success(`${action}成功`)
              PubSub.publish('TablePage', {type: this.id ? 'edit' : 'add'})
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })

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

<style lang="scss" scoped>
@import "@/assets/css/element-variables";
</style>
