<template>
  <div class="edit-add-detail">
    <div class="edit-add-detail-new-content">
      <div
        v-loading="false"
        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="160px"
        >
          <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="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="回访时间" prop="revisitTime">
                <el-date-picker
                  v-model="addEditForm.revisitTime"
                  default-time="12:00:00"
                  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="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="24">
              <el-form-item label="回访结果" prop="revisitResult">
                <el-radio-group
                  v-model="addEditForm.revisitResult"
                  size="medium"
                >
                  <el-radio
                    v-for="(item, index) in getDictionaryByCode('hfjg')"
                    :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="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="收费相关附件" prop="rescueFiles">
                <el-upload
                  ref="upload"
                  :action="actionUrl + '/file/v1/fileUpload'"
                  :data="{
                    file: JSON.stringify({storeType: 'minio'}),
                  }"
                  :file-list="addEditForm.rescueFiles"
                  :headers="headers"
                  :multiple="false"
                  :on-error="handleError"
                  :on-preview="handlePreview"
                  :on-remove="rescueHandleRemove"
                  :on-success="rescueHandleSuccess"
                  name="files"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="其他附件" prop="appraiseFiles">
                <el-upload
                  ref="upload"
                  :action="actionUrl + '/file/v1/fileUpload'"
                  :data="{
                    file: JSON.stringify({storeType: 'minio'}),
                  }"
                  :file-list="addEditForm.appraiseFiles"
                  :headers="headers"
                  :multiple="false"
                  :on-error="handleError"
                  :on-preview="handlePreview"
                  :on-remove="appraiseHandleRemove"
                  :on-success="appraiseHandleSuccess"
                  name="files"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="回访备注" prop="revisitMemo">
                <el-input
                  v-model="addEditForm.revisitMemo"
                  :rows="2"
                  clearable
                  placeholder="请输入回访备注"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="resultShow()" 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
            v-if="resultShow()"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="评价时间" prop="appraiseTime">
                <el-date-picker
                  v-model="addEditForm.appraiseTime"
                  default-time="12:00:00"
                  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
            v-if="resultShow()"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item
                class="score-form-item"
                label="评价分数"
                prop="appraiseScore"
              >
                <el-rate
                  v-model="addEditForm.appraiseScore"
                  allow-half
                  class="appraiseScore"
                  disabled-void-color="#43a1ff"
                  disabled-void-icon-class="el-icon-star-off"
                  style="width: 100%"
                >
                </el-rate>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="resultShow()"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="评价手机号" prop="appraiseTel">
                <el-input
                  v-model="addEditForm.appraiseTel"
                  clearable
                  placeholder="请输入评价手机号"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="resultShow()"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item class="isComplain" label="是否投诉">
                <el-radio-group v-model="addEditForm.isComplain" size="medium">
                  <el-radio
                    v-for="(item, index) in ifOptions"
                    :key="index"
                    :label="item.value"
                    :value="item.value"
                    border
                  >{{ item.label }}
                  </el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="resultShow()"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col v-if="addEditForm.isComplain" :span="8">
              <el-form-item label="投诉是否有效" prop="complainValid">
                <el-radio-group
                  v-model="addEditForm.complainValid"
                  size="medium"
                >
                  <el-radio
                    v-for="(item, index) in ifOptions"
                    :key="index"
                    :label="item.value"
                    :value="item.value"
                    border
                  >{{ item.label }}
                  </el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="resultShow()"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="是否出示收费标准" prop="isCost">
                <el-radio-group v-model="addEditForm.isCost" size="medium">
                  <el-radio
                    v-for="(item, index) in ifOptions"
                    :key="index"
                    :label="item.value"
                    :value="item.value"
                    border
                  >{{ item.label }}
                  </el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="resultShow()"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="是否给予正规发票" prop="isInvoice">
                <el-radio-group v-model="addEditForm.isInvoice" size="medium">
                  <el-radio
                    v-for="(item, index) in ifOptions"
                    :key="index"
                    :label="item.value"
                    :value="item.value"
                    border
                  >{{ item.label }}
                  </el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="resultShow()"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="是否满意服务态度" prop="isService">
                <el-radio-group v-model="addEditForm.isService" size="medium">
                  <el-radio
                    v-for="(item, index) in serviceOptions"
                    :key="index"
                    :label="item.value"
                    :value="item.value"
                    border
                  >{{ item.label }}
                  </el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="resultShow()"
            :gutter="24"
            style="flex-wrap: wrap; margin-left: 80px"
            type="flex"
          >
            <el-col :span="8">
              <el-form-item label="评价建议" prop="appraiseInfo">
                <el-input
                  v-model="addEditForm.appraiseInfo"
                  :rows="2"
                  placeholder="请输入评价建议"
                  type="textarea"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </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 {fileData, tableAdd, tableDetail, tableEdit} from '@/api/patrolAndRescue/obstacleClearingRescue/rescueFollowUp'
import {getDictionaryByCode} from '@/utils/dictionary'
import {mapState} from 'vuex'

export default {
  name: 'EditAddPage',
  props: {
    componentName: {
      default: 'EditAddPage',
      type: String
    }
  },
  data() {
    return {
      appointDialog: false,
      formLoading: true,
      addEditForm: {
        isComplain: 0,
        isCost: 1,
        isInvoice: 1,
        isService: 1,
        revisitResult: 1,
        appraiseScore: 0,
        rescueFiles: [],
        appraiseFiles: []
      },
      addEditRules: {
        appraiseTel: [
          {
            required: true,
            message: '评价手机号不能为空',
            trigger: ['change', 'blur']
          }
          // {
          //   pattern: /^1[3456789]\d{9}$/,
          //   message: '评价手机号输入有误',
          //   trigger: 'blur'
          // }
        ],
        revisitTime: [
          {
            required: true,
            message: '回访时间不能为空',
            trigger: ['change', 'blur']
          }
        ],
        revisitResult: [
          {
            required: true,
            message: '回访结果不能为空',
            trigger: ['change', 'blur']
          }
        ],
        appraiseTime: [
          {
            required: true,
            message: '评价时间不能为空',
            trigger: ['change']
          }
        ],
        appraiseScore: [
          {
            required: true,
            message: '评价分数不能为空',
            trigger: ['change']
          }
          // {
          //   pattern: /^[0-5]$/, message: '评价分数在0~5之间', trigger: 'blur'
          // }
        ],
        isComplain: [
          {
            required: true,
            message: '投诉是否有效',
            trigger: ['change']
          }
        ],
        isCost: [
          {
            required: true,
            message: '是否出示收费标准',
            trigger: ['change']
          }
        ],
        isInvoice: [
          {
            required: true,
            message: '是否给予正规发票',
            trigger: ['change']
          }
        ],
        isService: [
          {
            required: true,
            message: '是否满意服务态度',
            trigger: ['change']
          }
        ]
      },
      saveLoading: false, // 上传loading
      ifOptions: [
        {label: '否', value: 0},
        {label: '是', value: 1}
      ],
      serviceOptions: [
        {label: '不满意', value: 0},
        {label: '满意', value: 1}
      ]
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  created() {
  },
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      this.addEditForm.rescueId = data.id
      this.$set(this.addEditForm, 'appraiseTel', data.carUserTel ? data.carUserTel : '')
      if (data.appraiseId) {
        this.getDetail(data.appraiseId)
      } else {
        this.defalutFileChange(data.id)
      }
    })
  },
  computed: {
    actionUrl: (_) => window.context.portal,
    previewUrl: (_) =>
      window.context.portal + '/file/onlinePreviewController/v1/getFileById_',
    downloadUrl: (_) => window.context.portal + '/file/v1/downloadFile?fileId=',
    ...mapState({
      headers: (state) => ({
        Authorization: `Bearer ${state.login.currentUser.token}`
      })
    })
  },
  methods: {
    // 默认收费文件
    async defalutFileChange(rescueId) {
      this.addEditForm.rescueFiles = await fileData(rescueId)
      if (this.addEditForm.rescueFiles.length > 0) {
        this.addEditForm.rescueFiles = this.addEditForm.rescueFiles.map(item => {
          return {
            name: item.fileName,
            url: item.filePreviewUrl,
            ...item
          }
        })
      }
    },

    // 文件上传失败
    handleError() {
      this.$message.warning('文件上传失败')
    },
    // 已上传文件点击
    async handlePreview(file) {
      const fileId = file.fileId || file.response.fileId || '' // 文件ID
      const fileName = file.filePath || '' // 文件名
      if (!(fileId && fileName))
        return this.$message.warning('文件错误，请删除后重新上传')
      const browserOperablePattern = /\.(jpg|jpeg|png|gif|bmp|webp|pdf)$/i
      if (browserOperablePattern.test(fileName)) {
        window.open(this.previewUrl + fileId, '_blank')
      } else {
        window.open(this.downloadUrl + fileId, '_blank')
      }
    },
    // 文件删除后
    rescueHandleRemove(file) {
      const fileId = file.fileId || file.response.fileId || ''
      const index = this.addEditForm.rescueFiles.findIndex(
        (i) => i.fileId === fileId
      )
      if (index !== -1) this.addEditForm.rescueFiles.splice(index, 1)
    },
    // 文化上传成功
    rescueHandleSuccess(response) {
      const {
        fileId = '',
        fileName = '',
        size: fileSizes = 0,
        success
      } = response
      if (success) {
        this.addEditForm.rescueFiles.push({fileId, fileSizes, fileName, name: fileName})
      } else {
        this.$message.error('文件上传失败')
      }
      this.saveLoading = false
    },
    // 文件删除后
    appraiseHandleRemove(file) {
      const fileId = file.fileId || file.response.fileId || ''
      const index = this.addEditForm.appraiseFiles.findIndex(
        (i) => i.fileId === fileId
      )
      if (index !== -1) this.addEditForm.appraiseFiles.splice(index, 1)
    },
    // 文化上传成功
    appraiseHandleSuccess(response) {
      const {
        fileId = '',
        fileName = '',
        size: fileSizes = 0,
        success
      } = response
      if (success) {
        this.addEditForm.appraiseFiles.push({fileId, fileSizes, fileName, name: fileName})
      } else {
        this.$message.error('文件上传失败')
      }
      this.saveLoading = false
    },

    resultShow() {
      return !(this.addEditForm.revisitResult === 2 || this.addEditForm.revisitResult === 3 || this.addEditForm.revisitResult === 4)
    },
    offPage() {
      this.changePage('TablePage', 'edit')
    },
    getDictionaryByCode,
    // 打开页面执行
    openPage() {
      // this.$refs.mineMap?.map?.resize()
    },
    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      this[dialogName + 'Dialog'] = true
    },

    // 关闭页面执行
    closePage() {
      const {pubSub, addEditRules} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub,
        addEditRules
      })
      this.$refs.mineMap?.resetMap(_ => (this.mapLoading = false)) // 重置地图
      this.$nextTick(_ => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },
    // 获取详情
    async getDetail(appraiseId, id) {
      try {
        this.addEditForm = await tableDetail(appraiseId)
        const {appraiseScore = 0} = this.addEditForm
        this.addEditForm.appraiseScore = Number(appraiseScore)
        this.addEditForm.rescueFiles = this.addEditForm.rescueFiles ? this.addEditForm.rescueFiles : []
        this.addEditForm.appraiseFiles = this.addEditForm.appraiseFiles ? this.addEditForm.appraiseFiles : []
        if (this.addEditForm.appraiseFiles.length > 0) {
          this.addEditForm.appraiseFiles = this.addEditForm.appraiseFiles.map(item => {
            return {
              name: item.fileName,
              url: item.filePreviewUrl,
              ...item
            }
          })
        }
        if (this.addEditForm.rescueFiles.length > 0) {
          this.addEditForm.rescueFiles = this.addEditForm.rescueFiles.map(item => {
            return {
              name: item.fileName,
              url: item.filePreviewUrl,
              ...item
            }
          })
        }
      } finally {
        this.formLoading = false
      }
    },

    // 保存
    handleSave() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          let data = JSON.parse(JSON.stringify(this.addEditForm))
          const myInterFace = data.id ? tableEdit : tableAdd
          try {
            let {state, message, value} = await myInterFace(data)
            if (state) {
              message = data.id ? '编辑' : '新增'
              this.$message.success(`保存成功`)
              this.changePage('TablePage', data.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';

::v-deep .el-icon-star-off:before {
  font-size: 26.5px !important;
}

::v-deep .el-icon-star-on:before {
  font-size: 28px !important;
}

::v-deep .el-rate__item {
  .el-rate__icon {
    .el-rate__decimal {
      width: 50% !important;
      top: -0.3px;
      left: 0px;
      font-size: 20px !important;
    }
  }
}

::v-deep .el-rate__icon.hover {
  transform: scale(1) !important;
}

.score-form-item {
  ::v-deep .el-form-item__content {
    display: flex;
    align-items: center;

    .el-input {
      flex: 1;
      margin-right: 10px;
    }

    .appraiseScore {
      width: 150px;
    }
  }
}

::v-deep .el-rate__text {
  color: #ff9900 !important;
  font-size: 18px !important;
}

::v-deep .el-rate__icon {
  font-size: 24px !important;

  .el-rate__decimal {
    font-size: 24px !important;
  }
}

.number-input {
  ::v-deep .el-input__inner {
    font-size: 14px;
  }
}

.edit-add-detail-new-content {
  width: 100%;
  display: flex;
  height: 0;
  flex: 1;
  column-gap: 20px;

  .form-content {
    flex: 2;
  }

  .map-content {
    flex: 3;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: $--system-border-color3 0.5px 0.5px 5px 1px;

    ::v-deep.marker-tip {
      position: relative;
      background-image: url('~@/assets/img/patrolAndRescue/inspection-points-icon.png');
      background-size: cover;
      width: 48px !important;
      height: 48px !important;
      z-index: 999;

      &::after {
        position: absolute;
        content: '救援点位置';
        left: 100%;
        top: 8px;
        width: 80px;
        height: 25px;
        font-size: 16px;
        color: $--color-warning;
        text-align: center;
        line-height: 25px;
        padding: 5px 10px;
        background-color: rgba(darken($--color-warning, 70%), 0.9);
        border-radius: 3px;
        box-shadow: 0 0 6px rgba($--color-warning, 0.8);
        border: none;
        z-index: 999;
      }
    }
  }

  .stake-mark {
    ::v-deep .el-form-item__content {
      display: flex;
      justify-content: space-between;

      .pegVal-text2,
      .pegVal-text1 {
        padding-right: 10px;
        font-size: 16px;
        width: fit-content;
      }

      .pegVal-text2 {
        padding-left: 10px;
        font-size: 24px;
      }
    }
  }
}
</style>

<style lang="scss"></style>
