<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"
                width="100%"
                type="datetime"
                placeholder="选择日期时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="服务截止：" prop="serviceDeadline">
              <el-date-picker
                v-model="ruleForm.serviceDeadline"
                type="datetime"
                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 dropData"
                :key="index"
                :label="item.variableName"
                :value="item.variableCoding"
              ></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 dropData"
                :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 dropData2"
                :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 dropData2"
                :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 dropData2"
                :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>
              <el-form-item label="选择文件：" prop="delivery">
                <el-upload
                  :action="uploadUrl"
                  :on-success="handleUpAvatar"
                  :on-remove="handleRemove"
                  :show-file-list="fileList"
                  list-type="picture-card"
                  :limit="3"
                  :on-preview="handlePictureCardPreview"
                  :headers="{ accessToken: [accessToken] }"
                >
                  <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')">
                保存
              </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 } 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',
  setup() {
    const store = useStore()
    const formInfo = ref(null)
    const dialogImageUrl = ref('')
    const dialogVisible = ref(false)
    const disabled = ref(false)
    const accessToken = ref(store.state.user.accessToken)
    const dropData = ref([])
    const dropData2 = ref([])
    const platFormData = ref([])
    const ruleForm = ref({
      siteName: '',
      siteType: '',
      userCompany: '',
      operationTime: '',
      serviceDeadline: '',
      installedCapacity: '',
      powerSupplyType: '1',
      voltageLevel: '',
      siteAddress: '',
      longitude: '',
      latitude: '',
      region: '1',
      stationAreaId: '',

      demolitionStandardCoal1: '',
      demolitionStandardCoal: '1',
      rheologicalChange: '',
      routeId: '',

      faultStatus: '',
      realTimeLoad: '',
      totalElectricity: '',
      powerFactor: '',

      userName: '',
      phone: '',
      spareUserName: '',
      sparePhone: '',

      sitePictureOne: '',
      sitePictureTwo: '',
      sitePictureThree: '',
    })

    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 handleUpAvatar(res) {
      console.log('res')
      console.log(res)
      dataSet.fileList.push(res.data)
      console.log(dataSet.fileList)
    }
    //删除照片
    function handleRemove(res) {
      // console.log('删除')
      // console.log(res.name)

      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)
        }
      }
      dataSet.fileList.remove(res.name)

      console.log(dataSet.fileList)
    }

    //表单提交
    function submitForm() {
      ruleForm.value.sitePictureOne = dataSet.fileList[0]
      ruleForm.value.sitePictureTwo = dataSet.fileList[1]
      ruleForm.value.sitePictureThree = dataSet.fileList[2]

      ruleForm.value.operationTime
        ? (ruleForm.value.operationTime = parseTime(
            ruleForm.value.operationTime
          ))
        : ''
      ruleForm.value.serviceDeadline
        ? (ruleForm.value.serviceDeadline = parseTime(
            ruleForm.value.serviceDeadline
          ))
        : ''

      formInfo.value.validate((valid) => {
        if (valid) {
          store
          //  store.commit('TimeAll_function')
          // const time = store.state.Time_Data
          // ruleForm.value.operationTime = time[0]
          // ruleForm.value.serviceDeadline = time[1]

          api
            .siteAdd({
              site: {
                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: '1', //字段值待写活
              },
              siteDynamicProperties: {
                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,
              },
            })
            .then((requset) => {
              if (requset.status === 'SUCCESS') {
                ElMessage.success({
                  message: '新增成功',
                  type: 'success',
                })
                // if (props.dialogTitle === '新增') {
                //   ElMessage.success({
                //     message: '新增成功',
                //     type: 'success',
                //   })
                // } else {
                //   ElMessage.success({
                //     message: '修改成功',
                //     type: 'success',
                //   })
                // }
              } else {
                ElMessage.error(requset.msg)
              }
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }

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

    // 动态属性下拉请求
    function dynamicPropertiesDroplist(dataArea) {
      api.dynamicPropertiesDroplist({ dataArea: dataArea }).then((requset) => {
        if (requset.status === 'SUCCESS') {
          if (dataArea == 1) {
            //模拟量
            dropData2.value = requset.data
          } else {
            //状态量
            dropData.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)
        }
      })
    }

    onMounted(() => {
      platformList()
      dynamicPropertiesDroplist(2)
      dynamicPropertiesDroplist(1)
    })

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

      dropData,
      dropData2,
      platFormData,

      accessToken,
      ruleForm,
      rules: {
        siteName: [
          { required: true, message: '请输入站点名称', trigger: 'blur' },
          {
            min: 3,
            max: 11,
            message: '长度在 3 到 11 个字符',
            trigger: 'blur',
          },
        ],
        siteType: [
          { required: true, message: '请输入站点类型', trigger: 'blur' },
        ],
        userCompany: [
          { required: true, message: '请输入用户公司', trigger: 'blur' },
          {
            min: 3,
            max: 11,
            message: '长度在 3 到 11 个字符',
            trigger: 'blur',
          },
        ],
        operationTime: [
          { required: true, message: '请选择运投时间', trigger: 'change' },
        ],
        serviceDeadline: [
          { required: true, message: '请选择服务截止时间', trigger: 'change' },
        ],
        installedCapacity: [
          { required: true, message: '请输入装机容量', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur',
          },
        ],
        voltageLevel: [
          { required: true, message: '请输入电压等级', trigger: 'blur' },
        ],
        siteAddress: [
          { required: true, message: '请输入站点地址', trigger: 'blur' },
          {
            min: 3,
            max: 11,
            message: '长度在 3 到 11 个字符',
            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: 3,
            max: 11,
            message: '长度在 3 到 11 个字符',
            trigger: 'blur',
          },
        ],
        phone: [
          {
            required: true,
            message: '请输入联系方式1',
            trigger: 'blur',
          },
          {
            validator: validatorPhone,
            message: '输入的电话号码不正确',
            trigger: 'blur',
          },
        ],
        spareUserName: [
          { required: true, message: '请输入联系人2', trigger: 'blur' },
          {
            min: 3,
            max: 11,
            message: '长度在 3 到 11 个字符',
            trigger: 'blur',
          },
        ],
        sparePhone: [
          { required: true, message: '请输入联系方式2', trigger: 'blur' },
          {
            min: 3,
            max: 11,
            message: '长度在 3 到 11 个字符',
            trigger: 'blur',
          },
        ],
      },
      handleRemove,
      handlePictureCardPreview,
      submitForm,
      resetForm,

      handleUpAvatar,
    }
  },
})
</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>
