<template>
  <div class="siteManage-main basic-info-page">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="formInfo"
      label-width="110px"
      class="demo-ruleForm"
    >
      <el-row style="min-width: 1100px">
        <el-col :span="8" :gutter="20">
          <div class="grid-content bg-purple">
            <el-form-item label="站点名称：" prop="siteName">
              <el-input v-model="ruleForm.siteName"></el-input>
            </el-form-item>

            <el-form-item label="站点类型：" prop="siteType">
              <el-input v-model="ruleForm.siteType"></el-input>
            </el-form-item>
            <el-form-item label="用户公司：" prop="userCompany">
              <el-input v-model="ruleForm.userCompany"></el-input>
            </el-form-item>

            <el-form-item
              label="投运时间："
              prop="operationTime"
              style="margin-top: 0px"
            >
              <el-date-picker
                v-model="ruleForm.operationTime"
                style="width: 100%"
                type="date"
                placeholder="选择日期时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="服务截止：" prop="serviceDeadline">
              <el-date-picker
                v-model="ruleForm.serviceDeadline"
                type="date"
                placeholder="选择日期时间"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="装机容量：" prop="installedCapacity">
              <el-input v-model="ruleForm.installedCapacity"></el-input>
            </el-form-item>
            <el-form-item label="供电类型：" prop="powerSupplyType">
              <el-radio-group v-model="ruleForm.powerSupplyType">
                <el-radio label="1" value="1">单路</el-radio>
                <el-radio label="2" value="2">双路</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="电压等级：" prop="voltageLevel">
              <el-input v-model="ruleForm.voltageLevel"></el-input>
            </el-form-item>
            <el-form-item label="站点地址：" prop="siteAddress">
              <el-input v-model="ruleForm.siteAddress"></el-input>
            </el-form-item>

            <el-form-item label="所属区域：" prop="region">
              <el-radio-group v-model="ruleForm.region">
                <el-radio label="1">宝山</el-radio>
                <el-radio label="2">嘉定</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="所属台区：" prop="stationAreaId">
              <el-select v-model="ruleForm.stationAreaId" placeholder="请选择">
                <el-option
                  v-for="(item, index) in platFormData"
                  :key="index"
                  :label="item.platformAreaName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="站点坐标：" prop="longitude">
              <el-input v-model="ruleForm.longitude" placeholder="请输入经度">
                <i
                  :default-slot="suffix"
                  class="el-input__icon el-icon-location-outline"
                ></i>
              </el-input>
            </el-form-item>
            <el-form-item label="" prop="latitude">
              <el-input v-model="ruleForm.latitude" placeholder="请输入维度">
                <i
                  :default-slot="suffix"
                  class="el-input__icon el-icon-location-outline"
                ></i>
              </el-input>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8" :gutter="20">
          <!-- <el-form-item label="监察：" prop="region">
            <el-select v-model="ruleForm.region" placeholder="请选择">
              <el-option label="监察1" value="1"></el-option>
              <el-option label="监察2" value="2"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="折标准煤：" prop="demolitionStandardCoal1">
            <el-input v-model="ruleForm.demolitionStandardCoal1"></el-input>
          </el-form-item>
          <el-form-item label="折标准煤：" prop="demolitionStandardCoal">
            <el-radio-group v-model="ruleForm.demolitionStandardCoal">
              <el-radio label="1">电力（等价）</el-radio>
              <el-radio label="2">电力（当量）</el-radio>
            </el-radio-group>
            <div style="opacity: 0.45">0.000404吨标准煤/千瓦时</div>
          </el-form-item>

          <el-form-item label="流变变比" prop="rheologicalChange">
            <el-input v-model="ruleForm.rheologicalChange"></el-input>
          </el-form-item>
          <el-form-item label="所属线路" prop="routeId">
            <el-select v-model="ruleForm.routeId" placeholder="请选择">
              <el-option
                v-for="(item, index) in routeDropData"
                :key="index"
                :label="item.routeName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <a class="goArchive">现场档案</a>

          <div class="blockTitle mt-60 mb-20">动态属性</div>
          <el-form-item label="故障动态：" prop="faultStatus">
            <el-select v-model="ruleForm.faultStatus" placeholder="请选择">
              <el-option
                v-for="(item, index) in dropData2"
                :key="index"
                :label="item.variableName"
                :value="item.variableCoding"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="实时负荷：" prop="realTimeLoad">
            <el-select v-model="ruleForm.realTimeLoad" placeholder="请选择">
              <el-option
                v-for="(item, index) in dropData"
                :key="index"
                :label="item.variableName"
                :value="item.variableCoding"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="总用电量：" prop="totalElectricity">
            <el-select v-model="ruleForm.totalElectricity" placeholder="请选择">
              <el-option
                v-for="(item, index) in dropData"
                :key="index"
                :label="item.variableName"
                :value="item.variableCoding"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="功率因数：" prop="powerFactor">
            <el-select v-model="ruleForm.powerFactor" placeholder="请选择">
              <el-option
                v-for="(item, index) in dropData"
                :key="index"
                :label="item.variableName"
                :value="item.variableCoding"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" :gutter="20">
          <div class="grid-content bg-purple">
            <div class="grid-content bg-purple-light">
              <!-- 站点照片start -->
              <div class="blockTitle mb-20">站点照片</div>
              <!-- <img v-if="ruleForm.value.sitePictureOne" :src="ruleForm.value.sitePictureOne" alt=""> -->
              <el-form-item label="选择文件：" prop="delivery">
                <el-upload
                  :action="uploadUrl"
                  :on-success="handleUpAvatar"
                  :on-remove="handleRemove"
                  :on-change="handleChange"
                  :show-file-list="true"
                  list-type="picture-card"
                  :limit="3"
                  :file-list="fileListImages"
                  :on-preview="handlePictureCardPreview"
                  :headers="{ accessToken: [accessToken] }"
                  :on-exceed="overLength"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog v-model="dialogVisible" width="400px">
                  <img style="width: 100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
              </el-form-item>
              <!-- 站点照片end -->

              <el-form-item label="联系人：" prop="userName">
                <el-input v-model="ruleForm.userName"></el-input>
              </el-form-item>
              <el-form-item label="联系方式：" prop="phone">
                <el-input v-model="ruleForm.phone"></el-input>
              </el-form-item>
              <el-form-item label="联系人2：" prop="spareUserName">
                <el-input v-model="ruleForm.spareUserName"></el-input>
              </el-form-item>
              <el-form-item label="联系方式2：" prop="sparePhone">
                <el-input v-model="ruleForm.sparePhone"></el-input>
              </el-form-item>
            </div>
            <br />
            <el-form-item>
              <el-button
                type="primary"
                @click="submitForm('formInfo')"
                :disabled="isDisable"
              >
                保存
              </el-button>
              <!-- <el-button @click="resetForm('formInfo')">取消</el-button> -->
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, reactive, toRefs, watch } from 'vue'
import * as api from '@/api/siteManage/basicInfo'
import { ElMessage } from 'element-plus'

import { useStore } from 'vuex'
import { parseTime, validatorPhone } from '@/utils'

export default defineComponent({
  name: 'BasicInfo',
  props: {
    siteId: Number,
    siteName: String,
    groupingId: Number,
    activeName: String,
  },
  setup(props, context) {
    const fileImages = ref(window.PLATFROM_CONFIG.images)
    const store = useStore()
    const isDisable = ref(false)
    const routeDropData = ref([])
    const formInfo = ref(null)
    const formStatus = ref('')
    const dialogImageUrl = ref('')
    const dialogVisible = ref(false)
    const disabled = ref(false)
    const accessToken = ref(store.state.user.accessToken)
    const dropData = ref([])
    const fileListImages = ref([])
    const dropData2 = ref([])
    const platFormData = ref([])
    const ruleForm = ref({})

    const newArray = ref([])
    const dataSetRe = ref([])

    function handlePictureCardPreview(file) {
      console.log('file')
      console.log(file)
      dialogImageUrl.value = file.url
      dialogVisible.value = true
    }

    const dataSet = reactive({
      uploadUrl:
        window.PLATFROM_CONFIG.baseUrl +
        '/patrolInspectionDevice/pictureUpload',
      // uploadUrl:'https://wx.ewoogi.com/USKYOF/USKYOF.php/Home/MonitoringReporting/setUpload',
      fileList: [],
    })

    //图片个数限制
    function overLength() {
      ElMessage({
        message: '最多只能上传3张图片！',
        type: 'warning',
      })
    }

    // function uniqueArr(arr) {
    //   for (var i = 0; i < arr.length; i++) {
    //     for (var j = i + 1; j < arr.length; j++) {
    //       if (arr[i].name == arr[j].name) {
    //         alert('不支持同名文件上传')
    //         arr.splice(j, 1)
    //         j--
    //       }
    //     }
    //   }
    //   return arr
    // }

    // function handleChange(file, fileList) {
    //   // console.log('这是handleChange')
    //   // console.log('这是file', file)
    //   // console.log('这是fileList', fileList)
    //   fileList = uniqueArr(fileList)
    //    console.log('这是fileList', fileList)
    // }

    //上传成功的回调
    function handleUpAvatar(res) {
      // console.log(newArray.value.indexOf(res.data))
      // if(newArray.value.indexOf(res.data)!=-1){
      //   alert('上传重复')
      //   return

      // };

      dataSetRe.value = []
      dataSet.fileList = []
      newArray.value = []

      dataSet.fileList.push(res.data)

      dataSet.fileList.forEach(function (item) {
        dataSetRe.value.push({ url: fileImages.value + item })
      })

      if (fileListImages.value) {
        fileListImages.value = fileListImages.value.concat(dataSetRe.value)
      } else {
        fileListImages.value = dataSetRe.value
      }

      fileListImages.value.forEach(function (item) {
        newArray.value.push(item.url.substring(27))
      })

      console.log('newArray.value')
      console.log(newArray.value)
    }

    //删除照片
    function handleRemove(res) {
      newArray.value = []
      console.log('删除')
      console.log(res)
      console.log('fileListImages.value')
      console.log(fileListImages.value)

      Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
          if (this[i] == val) return i
        }
        return -1
      }
      Array.prototype.remove = function (val) {
        var index = this.indexOf(val)
        if (index > -1) {
          this.splice(index, 1)
        }
      }

      fileListImages.value = fileListImages.value.filter(
        (v) => v.url !== res.url
      )
      fileListImages.value.forEach(function (item) {
        newArray.value.push(item.url.substring(27))
      })

      console.log('newArray.value')
      console.log(newArray.value)
    }

    function resetForm() {
      formInfo.value.clearValidate()
    }

    // 动态属性下拉请求
    function dynamicPropertiesDroplist(dataArea) {
      api
        .dynamicPropertiesDroplist({ dataArea: dataArea, siteId: props.siteId })
        .then((requset) => {
          if (requset.status === 'SUCCESS') {
            if (dataArea == 1) {
              //模拟量
              dropData.value = requset.data
            } else {
              //状态量
              dropData2.value = requset.data
            }
          } else {
            ElMessage.error(requset.msg)
          }
        })
    }

    //台区下拉请求
    function platformList() {
      api.platformList({ size: 0 }).then((requset) => {
        if (requset.status === 'SUCCESS') {
          platFormData.value = requset.data.records
        } else {
          ElMessage.error(requset.msg)
        }
      })
    }

    //所属线路下拉
    function routeDroplist() {
      api.routeDroplist().then((requset) => {
        if (requset.status === 'SUCCESS') {
          routeDropData.value = requset.data
          console.log('routeDropData.value')
          console.log(routeDropData.value)
        } else {
          ElMessage.error(requset.msg)
        }
      })
    }

    //站点详情请求
    function getSite() {
      fileListImages.value = []

      api.getSite({ id: props.siteId }).then((requset) => {
        if (requset.status === 'SUCCESS') {
          console.log(requset.data[0])
          ruleForm.value = requset.data[0]
          ruleForm.value.region
            ? (ruleForm.value.region = requset.data[0].region.toString())
            : ''
          ruleForm.value.powerSupplyType = ruleForm.value.powerSupplyType
            ? requset.data[0].powerSupplyType.toString()
            : ''
          ruleForm.value.demolitionStandardCoal
            ? (ruleForm.value.demolitionStandardCoal =
                requset.data[0].demolitionStandardCoal.toString())
            : ''

          if (requset.data[0].sitePictureOne) {
            fileListImages.value.push({
              url: fileImages.value + requset.data[0].sitePictureOne,
            })
          }
          if (requset.data[0].sitePictureTwo) {
            fileListImages.value.push({
              url: fileImages.value + requset.data[0].sitePictureTwo,
            })
          }
          if (requset.data[0].sitePictureThree) {
            fileListImages.value.push({
              url: fileImages.value + requset.data[0].sitePictureThree,
            })
          }
          if (store.state.basicInfoSiteName && props.siteId) {
            ruleForm.value.siteName = store.state.basicInfoSiteName //站点名称重新赋值
          }

          console.log('fileListImages.value')
          console.log(fileListImages.value)
        } else {
          ElMessage.error(requset.msg)
        }
      })
    }

    //表单提交
    function submitForm() {
      ruleForm.value.sitePictureOne = newArray.value[0] ? newArray.value[0] : ''
      ruleForm.value.sitePictureTwo = newArray.value[1] ? newArray.value[1] : ''
      ruleForm.value.sitePictureThree = newArray.value[2]
        ? newArray.value[2]
        : ''

      ruleForm.value.operationTime
        ? (ruleForm.value.operationTime = parseTime(
            ruleForm.value.operationTime
          ).substring(0, 10))
        : ''
      ruleForm.value.serviceDeadline
        ? (ruleForm.value.serviceDeadline = parseTime(
            ruleForm.value.serviceDeadline
          ).substring(0, 10))
        : ''

      formInfo.value.validate((valid) => {
        // alert(formStatus.value)
        if (valid) {
          isDisable.value = true

          store
          //  store.commit('TimeAll_function')
          // const time = store.state.Time_Data
          // ruleForm.value.operationTime = time[0]
          // ruleForm.value.serviceDeadline = time[1]

          var params = {
            site: {
              id: props.siteId,
              siteName: ruleForm.value.siteName,
              installedCapacity: ruleForm.value.installedCapacity,
              siteAddress: ruleForm.value.siteAddress,
              region: ruleForm.value.region,
              stationAreaId: ruleForm.value.stationAreaId,
              longitude: ruleForm.value.longitude,
              latitude: ruleForm.value.latitude,
              userName: ruleForm.value.userName,
              phone: ruleForm.value.phone,
              spareUserName: ruleForm.value.spareUserName,
              sparePhone: ruleForm.value.sparePhone,
              rheologicalChange: ruleForm.value.rheologicalChange,
              routeId: ruleForm.value.routeId,
              groupingId: props.groupingId,
            },
            siteDynamicProperties: {
              id: ruleForm.value.siteDynamicPropertiesId,
              siteType: ruleForm.value.siteType,
              userCompany: ruleForm.value.userCompany,
              operationTime: ruleForm.value.operationTime,
              serviceDeadline: ruleForm.value.serviceDeadline,
              powerSupplyType: ruleForm.value.powerSupplyType,
              voltageLevel: ruleForm.value.voltageLevel,
              demolitionStandardCoal: ruleForm.value.demolitionStandardCoal,
              demolitionStandardCoal1: ruleForm.value.demolitionStandardCoal1,
              faultStatus: ruleForm.value.faultStatus,
              realTimeLoad: ruleForm.value.realTimeLoad,
              totalElectricity: ruleForm.value.totalElectricity,
              powerFactor: ruleForm.value.powerFactor,
              sitePictureOne: ruleForm.value.sitePictureOne,
              sitePictureTwo: ruleForm.value.sitePictureTwo,
              sitePictureThree: ruleForm.value.sitePictureThree,
            },
            id: formStatus.value == '修改' ? 1 : 0,
          }

          if (formStatus.value == '新增') {
            params.site.groupingId = props.groupingId
          }

          api.siteAdd(params).then((requset) => {
            if (requset.status === 'SUCCESS') {
              ElMessage.success({
                message: '保存成功',
                type: 'success',
              })

              store.state.basicInfoSiteName = '' //新增成功后存储的站点名称设为空

              setTimeout(() => {
                isDisable.value = false //点击一次时隔两秒后才能再次点击
              }, 2000)

              formStatus.value = '修改'
              context.emit('func')
            } else {
              ElMessage.error(requset.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }

    //监听变化
    watch(
      () => props.siteId,
      (newVal) => {
        // alert(1)
        // alert(newVal)
        console.log('newVal')
        console.log(newVal)
        if (props.activeName == 'first') {
          dataSet.fileList = []
          newArray.value = []

          resetForm()
        

          

          getSite()
          dynamicPropertiesDroplist(2)
          dynamicPropertiesDroplist(1)

          
        }
      }
    )
    watch(
      () => props.activeName,
      (newVal) => {
        if (newVal == 'first') {
          dataSet.fileList = []
          newArray.value = []

          resetForm()
          
          getSite()
          dynamicPropertiesDroplist(2)
          dynamicPropertiesDroplist(1)
        }
      }
    )
    watch(
      () => store.state.basicInfoSiteName,
      (newVal) => {
        if (newVal == '') {
          formStatus.value = '修改'
          resetForm()
          // getSite()
          // dynamicPropertiesDroplist(2)
          // dynamicPropertiesDroplist(1)
        }
      }
    )

    onMounted(() => {
      if (store.state.basicInfoSiteName && !props.siteId) {
        // alert('新增站点不带模板')
        formStatus.value = '新增'
      }
      if (store.state.basicInfoSiteName && props.siteId) {
        // alert('新增站点带模板')
        formStatus.value = '新增'
        getSite()
      }
      if (store.state.basicInfoSiteName == '') {
        // alert('修改')
        formStatus.value = '修改'
        getSite()
      }
      if (props.activeName == 'first') {
        if (store.state.basicInfoSiteName) {
          ruleForm.value.siteName = store.state.basicInfoSiteName
        }
        platformList()
        routeDroplist()
        dynamicPropertiesDroplist(2)
        dynamicPropertiesDroplist(1)
      }
    })

    return {
      ...toRefs(dataSet),
      formInfo,
      dialogImageUrl,
      dialogVisible,
      disabled,

      dropData,
      dropData2,
      platFormData,
      fileListImages,

      overLength,

      accessToken,
      ruleForm,
      resetForm,
      rules: {
        siteName: [
          { required: true, message: '请输入站点名称', trigger: 'blur' },
          {
            min: 1,
            max: 11,
            message: '长度在 1 到 11 个字符',
            trigger: 'blur',
          },
        ],
        siteType: [
          { required: true, message: '请输入站点类型', trigger: 'blur' },
        ],
        userCompany: [
          { required: true, message: '请输入用户公司', trigger: 'blur' },
          {
            min: 1,
            max: 11,
            message: '长度在 1 到 11 个字符',
            trigger: 'blur',
          },
        ],
        operationTime: [
          { required: true, message: '请选择运投时间', trigger: 'change' },
        ],
        serviceDeadline: [
          { required: true, message: '请选择服务截止时间', trigger: 'change' },
        ],
        installedCapacity: [
          { required: true, message: '请输入装机容量', trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur',
          },
        ],
        voltageLevel: [
          { required: true, message: '请输入电压等级', trigger: 'blur' },
        ],
        siteAddress: [
          { required: true, message: '请输入站点地址', trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur',
          },
        ],
        stationAreaId: [
          { required: true, message: '请选择所属台区', trigger: 'change' },
        ],
        longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
        latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
        demolitionStandardCoal1: [
          { required: true, message: '请输入折煤标准', trigger: 'blur' },
        ],
        routeId: [
          { required: true, message: '选择所属线路', trigger: 'change' },
        ],
        rheologicalChange: [
          { required: true, message: '请输入流变变比', trigger: 'blur' },
        ],

        userName: [
          { required: true, message: '请输入联系人1', trigger: 'blur' },
          {
            min: 1,
            max: 11,
            message: '长度在 1 到 11 个字符',
            trigger: 'blur',
          },
        ],
        phone: [
          {
            required: true,
            message: '请输入联系方式1',
            trigger: 'blur',
          },
          {
            validator: validatorPhone,
            message: '输入的电话号码不正确',
            trigger: 'blur',
          },
        ],
        spareUserName: [
          { required: true, message: '请输入联系人2', trigger: 'blur' },
          {
            min: 1,
            max: 11,
            message: '长度在 1 到 11 个字符',
            trigger: 'blur',
          },
        ],
        sparePhone: [
          { required: true, message: '请输入联系方式2', trigger: 'blur' },
          {
            min: 1,
            max: 11,
            message: '长度在 1 到 11 个字符',
            trigger: 'blur',
          },
        ],
      },
      handleRemove,
      handlePictureCardPreview,
      submitForm,
      routeDropData,
      handleUpAvatar,
      fileImages,
      getSite,
      isDisable,
      // handleChange,
      // uniqueArr,

      newArray,
      dataSetRe,
    }
  },
})
</script>

<style lang="scss">
.basic-info-page {
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100% !important;
  }
  // .el-icon-zoom-in {
  //   display: none;
  // }
  // .el-upload-list--picture-card .el-upload-list__item-actions span + span {
  //   margin-left: 0;
  // }
}
</style>
