<template>
  <view class="u-page">
    <u-navbar
      title="实时灾情上报"
      @leftClick="navigateBack"
      safeAreaInsetTop
      fixed
      placeholder
    ></u-navbar>
    <view class="info">
      <view class="u-demo-block__content">
        <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
        <!-- 工程详情上报 -->
        <u--form
          labelPosition="left"
          :model="formList"
          ref="form2"
          labelWidth="100"
        >
          <u-form-item
            label="灾害发生时间"
            prop="projectName"
            @click="
              isTime2 = true
              hideKeyboard()
            "
            :borderBottom="false"
            ref="item1"
          >
            <u--input
              placeholder="请选择"
              v-model="formList.otime"
              suffixIcon="arrow-right"
              suffixIconStyle="color: #909399"
            ></u--input>
          </u-form-item>
          <u-form-item
            label="严重程度"
            prop="severityList"
            :borderBottom="false"
            @click="
              isseverity = true
              hideKeyboard()
            "
            ref="item1"
          >
            <u--input
              placeholder="请选择"
              v-model="formList.severity"
              suffixIcon="arrow-right"
              suffixIconStyle="color: #909399"
            ></u--input>
          </u-form-item>
          <!-- @click="toMap" -->
          <u-form-item
            label="灾害发生地点"
            prop="address"
            :borderBottom="false"
            ref="item1"
          >
            <u--input
              placeholder="请输入"
              v-model="formList.address"
              suffixIconStyle="color: #909399"
            ></u--input>
          </u-form-item>
          <u-form-item label="经度：" :borderBottom="false" ref="item1">
            <u--input
              placeholder="请选择"
              v-model="formList.lgtd"
              suffixIconStyle="color: #909399"
            ></u--input>
          </u-form-item>
          <u-form-item label="纬度" :borderBottom="false" ref="item1">
            <u--input
              placeholder="请选择"
              v-model="formList.lttd"
              suffixIconStyle="color: #909399"
            ></u--input>
          </u-form-item>

          <!-- 水位(m) -->
          <u-form-item
            label="灾情描述"
            prop="ddscrib"
            :borderBottom="false"
            ref="item3"
          >
            <u--textarea
              placeholder="请输入"
              v-model="formList.ddscrib"
              count
            ></u--textarea>
          </u-form-item>
          <!-- 管控责任人： -->
          <u-form-item label="伤亡人数" prop="dpcount" ref="item3">
            <u--input
              v-model="formList.dpcount"
              placeholder="请输入"
              border="surround"
              clearable
            ></u--input>
          </u-form-item>
          <!-- 出库流量     (m³/s)： -->
          <u-form-item
            label="失踪人数"
            prop="mpcount"
            :borderBottom="false"
            ref="item3"
          >
            <u--input
              v-model="formList.mpcount"
              placeholder="请输入"
              type="number"
              clearable
              border="surround"
            ></u--input>
          </u-form-item>
          <u-form-item
            label="转移人数"
            prop="spcount"
            :borderBottom="false"
            ref="item3"
          >
            <u--input
              v-model="formList.spcount"
              placeholder="请输入"
              type="number"
              clearable
              border="surround"
            ></u--input>
          </u-form-item>
          <u-form-item
            label="损毁房屋(间)"
            prop="chcount"
            :borderBottom="false"
            ref="item3"
          >
            <u--input
              v-model="formList.chcount"
              placeholder="请输入"
              type="number"
              clearable
              border="surround"
              @blur="BlurText($event)"
            ></u--input>
          </u-form-item>
          <u-form-item
            label="直接经济损失 (万元)"
            prop="elose"
            :borderBottom="false"
            ref="item3"
          >
            <u--input
              v-model="formList.elose"
              placeholder="请输入"
              type="number"
              clearable
              border="surround"
              @blur="BlurText($event)"
            ></u--input>
          </u-form-item>

          <u-form-item
            label="过程降雨量(mm)"
            prop="pfrain"
            :borderBottom="false"
            ref="item3"
          >
            <u--input
              v-model="formList.pfrain"
              placeholder="请输入"
              type="number"
              clearable
              border="surround"
              @blur="BlurText($event)"
            ></u--input>
          </u-form-item>
          <!-- 其他运行情况 -->
          <u-form-item
            label="其他情况说明"
            prop="remark"
            :borderBottom="false"
            ref="item3"
          >
            <u--textarea
              placeholder="请输入"
              v-model="formList.remark"
              count
            ></u--textarea>
          </u-form-item>
          <u-form-item
            label="附件"
            prop="fileList"
            :borderBottom="false"
            ref="item3"
          >
            <u-upload
              :fileList="fileList1"
              @afterRead="afterRead"
              @delete="deletePic"
              name="1"
              multiple
              :maxCount="10"
              :previewFullImage="true"
            ></u-upload>
          </u-form-item>
        </u--form>

        <u-button
          type="primary"
          text="提交"
          customStyle="margin-top: 50px"
          @click="submit"
        ></u-button>

        <!-- 下拉选择 -->

        <u-datetime-picker
          :show="isTime2"
          v-model="valueTime2"
          mode="date"
          @confirm="confirm2"
          @cancel="cancel2"
        ></u-datetime-picker>
        <!--  mode="top" -->
        <view v-if="isName">
          <u-popup
            :show="isName"
            @close="isName = false"
            mode="right"
            @open="open"
          >
            <view style="padding: 30px 20px">
              <view class="tabs_h">
                <div
                  class="leftTab"
                  :class="{ activetextTypeTab: showTextTypeTab == 1 }"
                  @click="tabChange(1)"
                >
                  {{ namelabel }}
                </div>
                <div
                  class="rightTab"
                  :class="{ activetextTypeTab: showTextTypeTab == 2 }"
                  @click="tabChange(2)"
                >
                  {{ gclabel }}
                </div>
              </view>
              <!-- 水电站和水库 -->
              <view class="" v-if="isSk">
                <div
                  class="ul_list"
                  :class="{ activeTypeClass: activeType == 1 }"
                  @click="todetail(1, '水库')"
                >
                  <div class="left">水库</div>
                  <u-icon
                    v-if="activeType == 1"
                    name="checkmark"
                    color="#2286f6"
                    size="20"
                  ></u-icon>
                </div>

                <div
                  class="ul_list"
                  :class="{ activeTypeClass: activeType == 2 }"
                  @click="todetail(2, '水电站')"
                >
                  <div class="left">水电站</div>
                  <u-icon
                    v-if="activeType == 2"
                    name="checkmark"
                    color="#2286f6"
                    size="20"
                  ></u-icon>
                </div>
              </view>
              <!-- 具体水库或者水电站 -->
              <view v-else style="height: 300px; overflow-y: auto">
                <div v-for="(item, index) in resList" :key="index">
                  <div
                    class="ul_list"
                    :class="{ activeTypeClass: item.isShow }"
                    @click="infoClick(item)"
                  >
                    <div class="left">{{ item.resName }}</div>
                    <u-icon
                      v-if="item.isShow"
                      name="checkmark"
                      color="#2286f6"
                      size="20"
                    ></u-icon>
                  </div>
                </div>
              </view>
            </view>
          </u-popup>
        </view>

        <!-- 严重程度 -->
        <u-action-sheet
          :show="isseverity"
          :actions="severityList"
          title="请选择"
          @close="isseverity = false"
          @select="severitySelect"
        >
        </u-action-sheet>

        <!-- 是否已管控 -->
        <u-action-sheet
          :show="isControlled"
          :actions="actions"
          title="请选择"
          @close="isControlled = false"
          @select="controlledSelect"
        >
        </u-action-sheet>
      </view>
    </view>
  </view>
</template>

<script>
import moment from 'moment'
export default {
  data () {
    return {
      showTextTypeTab: 1,
      activeType: '',
      valueTime2: Number(moment()),
      isSk: true,
      isTime2: false,
      resList: [],
      key: '',
      title: {
        1: '运行情况上报',
        2: '工程险情上报',
        3: '实时灾情上报'
      },
      namelabel: '请选择',
      gclabel: '工程',
      fileList1: [],
      disabled1: false,
      tips: '',
      value: '',
      showCalendar: false,
      showBirthday: false,
      formList: {
        otime: '',
        severity: '', //   严重程度（1一般险情 2较大险情 3重大险情 4特别重大险情）
        address: '',
        lgtd: '',
        lttd: '',
        ddscrib: '',
        dpcount: '',
        mpcount: '',
        chcount: '',
        spcount: '',
        elose: '',
        remark: ''
      },

      fileIds: [],
      isControlled: false,
      isseverity: false, // 严重程度
      showSex: false,
      isRelease: false,
      isName: false,

      severityList: [
        {
          name: '一般险情'
        },
        {
          name: '较大险情'
        },
        {
          name: '重大险情'
        },
        {
          name: '特别重大险情'
        }
      ],

      actions: [
        {
          name: '是'
        },
        {
          name: '否'
        }
      ],
      rules: {
        otime: [
          {
            type: 'string',
            required: true,
            message: '请选择时间',
            trigger: ['blur', 'change']
          }
        ]
      },
      projectType: 1
    }
  },
  onLoad (options) {
    this.key = options.key
    console.log('搜索框22', options.key)

    this.getresList()
  },
  onReady () {
    console.log('搜索框22key', this.key)
    // 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
    this.$refs.form2.setRules(this.rules)
  },
  methods: {
    async getresList () {
      let res = null
      this.resList = []
      res = await uni.$http.get('/gunshiApp/xfflood/webi/resList')
      this.resList = res.data.data.map(item => {
        item.isShow = false

        return item
      })
    },

    async gethystList () {
      this.resList = []
      let res = await uni.$http.get('/gunshiApp/xfflood/webi/hystList')
      console.log('res', res.data.data)
      this.resList = res.data.data.map(item => {
        item.isShow = false
        item.resName = item.hystName

        return item
      })
    },

    tabChange (val) {
      this.showTextTypeTab = val
      if (val == 1) {
        this.isSk = true
      } else {
        this.isSk = false
      }
    },
    todetail (val, title) {
      this.activeType = val
      this.showTextTypeTab = 2
      this.isSk = false
      this.namelabel = title
      this.projectType = val
      if (val == 1) {
        this.getresList()
      } else {
        this.gethystList()
      }
    },
    infoClick (obj) {
      if (this.activeType == 1) {
        this.resList = this.resList.map(item => {
          if (item.resCode == obj.resCode) {
            item.isShow = true
            this.gclabel = item.resName
            this.formList.projectName = item.resName
          } else {
            item.isShow = false
          }
          return item
        })
      } else {
        this.resList = this.resList.map(item => {
          if (item.hystCode == obj.hystCode) {
            item.isShow = true
            this.gclabel = item.resName
            this.formList.projectName = item.resName
          } else {
            item.isShow = false
          }
          return item
        })
      }
    },
    // 删除图片
    deletePic (event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },
    // 新增图片
    async afterRead (event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map(item => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: 'success',
            message: '',
            url: result
          })
        )
        fileListLen++
      }
    },
    uploadFilePromise (url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: `${uni.$http.baseUrl}/gunshiApp/xfflood/iaCHsfwater/file/upload/singleSimple`,
          filePath: url,
          name: 'file',
          success: res => {
            setTimeout(() => {
              resolve(res.data)
            }, 1000)
          }
        })
      })
    },

    open () {},

    navigateBack () {
      uni.navigateBack()
    },

    severitySelect (e) {
      console.log('severitySelect0', e)
      this.formList.severity = e.name
      this.$refs.form2.validateField('severity')
    },
    controlledSelect (e) {
      this.formList.isControlled = e.name
      this.$refs.form2.validateField('isControlled')
    },

    submit () {
      this.$refs.form2
        .validate()
        .then(res => {
          uni.$u.toast('校验通过', res)
          debugger
          let params = Object.assign(this.formList)
          // 严重程度（1一般险情 2较大险情 3重大险情 4特别重大险情
          if (this.formList.severity == '一般险情') {
            params.severity = 1
          } else if (this.formList.severity == '较大险情') {
            params.severity = 2
          } else if (this.formList.severity == '重大险情') {
            params.severity = 3
          } else if (this.formList.severity == '特别重大险情') {
            params.severity = 4
          }
          params.adcd = ''

          if (this.fileList1.length > 0) {
            params.fileId = this.fileList1.map(item => {
              return JSON.parse(item.url).data.fileId
            })
          }

          uni.$http
            .post('/gunshiApp/xfflood/iaCHsfwater/insert', params)
            .then(res => {
              console.log('this.---', res)
              if (res.data.code == 200) {
                console.log('this.model122', res.data)
                uni.reLaunch({
                  url: '/pages/xxsb/index'
                })
              }
            })
        })
        .catch(errors => {
          uni.$u.toast('校验失败', errors)
          console.log('校验失败')
        })

      // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
    },
    reset () {
      const validateList = ['projectName', 'radiovalue1']
      this.$refs.form1.resetFields()
      this.$refs.form1.clearValidate()
      setTimeout(() => {
        this.$refs.form1.clearValidate(validateList)
        // 或者使用 this.$refs.form1.clearValidate()
      }, 10)
    },
    hideKeyboard () {
      uni.hideKeyboard()
    },
    confirm2 (val) {
      console.log(
        '点击确定按钮时触发',
        val.value,
        moment(val.value).format('YYYY-MM-DD HH:mm:ss')
      )

      this.valueTime2 = Number(val)
      this.formList.otime = moment(val.value).format('YYYY-MM-DD HH:mm:ss')
      this.isTime2 = false
    },
    cancel2 () {
      console.log('取消')
      this.isTime2 = false
    },
    toMap () {
      uni.navigateTo({
        url: `./map`
      })
    },
    // 过滤字符串
    BlurText (e) {
      console.log('e', e)
      let reg = /^\d+$/.test(e)
      if (!reg) {
        // this.
        console.log('22e', e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  font-size: 14px;
  background-color: #f3f5f8;
}
.tabs_h {
  display: flex;
  // justify-content: center;
  align-items: center;
  height: 56rpx;
  line-height: 88rpx;
  background-color: #fff;
  margin-bottom: 12rpx;
  text-align: center;
}
.leftTab {
  // width: 80px;
  margin-right: 20px;
}
.rightTab {
  // width: 80px;
}
.activetextTypeTab,
.activetextTypeTab:hover {
  border-bottom: 3rpx solid #2286f6;
  color: #026be0;
}
.activeTypeClass,
.activeTypeClass:hover {
  color: #026be0;
}

.nav_bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-top: 30px;
  padding-top: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #dfdfdf;
  box-shadow: 0 5px 10px -8px #dfdfdf inset;
  background-color: #fff;
  margin-bottom: 12rpx;
}
.nav_bar_tit {
  text-align: center;
}
.info {
  background-color: #fff;
  margin-bottom: 12rpx;
  padding: 20px;
}

.fl {
  display: flex;
  justify-content: start;
  align-items: left;
}
.flsb {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.u-image {
  width: 100%; /* 或者其他尺寸 */
  transition: transform 0.3s; /* 平滑的放大效果 */
}
.ul_list {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 48px;
  // border-bottom: 1px solid #dfdfdf;
}
</style>
