<template>
  <content-wrap>
    <section class="view-wrapper">
      <section class="flex-1">
        <section class="mb-40px">
          <section class="title-wrapper"> 基本信息</section>
          <el-form :rules="formRules" :model="formData" ref="formRef" label-width="100px">
            <section class="base-form">
              <el-form-item label="企业名称" prop="enterprisesName">
                <el-input v-model="formData.enterprisesName" placeholder="请输入企业名称" />
              </el-form-item>
              <el-form-item label="所属区域" prop="region">
                <el-select v-model="formData.region" placeholder="请选择所属区域" clearable>
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.ENTERPRISES_AREA)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="企业地址" prop="address">
                <el-input
                  v-model="formData.address"
                  placeholder="请选择企业地址"
                  readonly
                  @click="getGaps"
                >
                  <template #append>
                    <Icon icon="ep:position" @click.stop="getGaps" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="行业类别" prop="tags">
                <el-select
                  v-model="formData.tags"
                  placeholder="请选择行业类型"
                  clearable
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                >
                  <el-option
                    v-for="dict in typeList"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="企业介绍" class="form-textarea" prop="introduction">
                <el-input
                  v-model="formData.introduction"
                  placeholder="请输入企业介绍"
                  type="textarea"
                  maxlength="500"
                  show-word-limit
                  resize="none"
                />
              </el-form-item>
              <el-form-item label="环保负责人" prop="contactName">
                <el-input v-model="formData.contactName" placeholder="请输入负责人名称" />
              </el-form-item>
              <el-form-item label="联系方式" prop="environmentalContactPhone">
                <el-input
                  v-model="formData.environmentalContactPhone"
                  placeholder="请输入负责人联系方式"
                />
              </el-form-item>
              <el-form-item label="企业照片" prop="photo" class="form-photo">
                <FileUploader
                  v-model="formData.photo"
                  :limit="6"
                  height="148px"
                  width="148px"
                  ref="fileUploadRef"
                />
              </el-form-item>
              <section class="form-sub-title"> 执法配置</section>
              <el-form-item label="执法人员" prop="userId">
                <el-select
                  v-model="formData.userId"
                  placeholder="请选择执法人员"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in userList"
                    :key="item.userId"
                    :label="item.realName"
                    :value="item.userId"
                    popper-class="user-wrapper"
                  >
                    <el-avatar :src="item.avatar" :size="30" /> <span>{{ item.realName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="签到半径" prop="signRadius">
                <el-input-number
                  v-model="formData.signRadius"
                  :min="10"
                  :step="1"
                  placeholder="请输入执法半径"
                  controls-position="right"
                  class="!w-100%"
                >
                  <template #suffix>
                    <span>米</span>
                  </template>
                </el-input-number>
              </el-form-item>
            </section>
          </el-form>
        </section>
      </section>
      <section>
        <section class="title-wrapper"> 相关资质 </section>
        <section class="prove-wrapper">
          <section class="prove" v-for="(prove, index) in proveList" :key="index">
            <el-image
              :src="prove.files[0].url"
              :preview-src-list="prove.files[0]"
              :initial-index="0"
              class="border-rounded-6px h-130px mb-12px"
            />
            <section class="flex flex-col gap-4px items-center">
              <span class="font-bold">
                {{ getDictLabel(DICT_TYPE.ENTERPRISES_QUA, prove.qualificationName) }}
              </span>
              <span class="text-14px">{{ prove.enterpriseAuth }}</span>
              <span class="text-14px color-#606266" v-if="prove.qualificationName != 99">
                {{ formatDate(prove.expiryDate, 'YYYY年M月D日') }}到期
              </span>
              <span v-else>永久</span>
            </section>
          </section>
          <section class="add-prove" @click="addProve">
            <Icon icon="ep:plus" :size="30" />
          </section>
        </section>
      </section>
    </section>
    <section>
      <el-button @click="submit">保存</el-button>
    </section>
  </content-wrap>

  <GpsDialog ref="GpsDialogRef" @success="setGps" />
  <ProveForm ref="proveFormRef" @add-prove="setProve" />
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE, getDictLabel } from '@/utils/dict'
import { TagLibraryApi } from '@/api/system/taglibrary'
import { getEnterpriseManager } from '@/api/system/user'
import GpsDialog from './components/getGpsByAmap.vue'
import ProveForm from '@/views/qualification/prove.vue'
import { formatDate } from '@/utils/formatTime'
import { EnterprisesApi } from '@/api/enterprises'
/** 企业 表单 */
defineOptions({ name: 'UpdateEnterprises' })
//行业类别
const typeList = ref([] as any)
const userList = ref([] as any)
const GpsDialogRef = ref()
const proveFormRef = ref()
const formRef = ref()
const formData = ref({
  id: undefined,
  departmentId: undefined,
  userId: undefined,
  type: undefined,
  region: undefined,
  enterprisesName: undefined,
  address: undefined,
  contactName: undefined,
  enterprisesStatus: undefined,
  environmentalContactPhone: undefined,
  registrationNumber: undefined,
  introduction: undefined,
  establishmentDate: undefined,
  gpsLocation: undefined,
  searchQuery: undefined,
  managerDeptId: undefined,
  ides: undefined,
  startUserSelectAssignees: undefined,
  enterpriseUserId: undefined,
  tags: undefined,
  photo: [] as any,
  signRadius: 30
} as any)
const formRules = reactive({
  type: [{ required: true, message: '企业类型不能为空', trigger: 'change' }],
  enterprisesName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
  contactName: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  environmentalContactPhone: [
    { required: true, message: '企业环保负责人联系电话不能为空', trigger: 'blur' }
  ],
  userId: [
    {
      required: true,
      message: '请选择执法人员',
      trigger: 'change'
    }
  ],
  signRadius: [
    {
      required: true,
      message: '请输入执法半径',
      trigger: 'change'
    }
  ],
  photo: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value.length > 0) {
          callback()
        } else {
          callback(new Error('企业照片不能为空'))
        }
      },
      trigger: 'change'
    }
  ],
  introduction: [
    {
      required: true,
      message: '请输入企业介绍',
      trigger: 'change'
    }
  ],
  address: [
    {
      required: true,
      message: '请输入企业地址',
      trigger: 'change'
    }
  ],
  tags: [
    {
      required: true,
      message: '请选择行业类别',
      trigger: 'change'
    }
  ],
  region: [
    {
      required: true,
      message: '请选择所属区域',
      trigger: 'change'
    }
  ]
})
const fileUploadRef = ref()
const proveList: any = ref([])
/** 查询搜索项列表 */
const getSelectOption = async () => {
  userList.value = await getEnterpriseManager()
  const res = await TagLibraryApi.tagLibraryList('hy')
  typeList.value = res[0].children.map((t) => {
    return {
      label: t.tagName,
      value: t.id
    }
  })
}

const setGps = (gps: any) => {
  formData.value.gpsLocation = [gps.location.lat, gps.location.lng]
  formData.value.address = `${gps.district}${gps.address}`
}

const getGaps = () => {
  if (formData.value.gpsLocation) {
    unref(GpsDialogRef).open({
      name: formData.value.enterprisesName,
      address: formData.value.address,
      location: {
        lat: formData.value.gpsLocation[0],
        lng: formData.value.gpsLocation[1]
      }
    })
  } else {
    unref(GpsDialogRef).open()
  }
}

const addProve = () => {
  unref(proveFormRef).open()
}

const submit = async () => {
  const validate = await unref(formRef).validate()
  if (!validate) return
  await unref(fileUploadRef).handlerUpload()
  console.log(formData.value, proveList.value)
  if (formData.value.id) {
    await EnterprisesApi.updateEnterprises(formData.value)
  } else {
    const data = {
      ...formData.value,
	    fileIds: formData.value.photo.map((i) => i.id),
	    gpsLocation:formData.value.gpsLocation.join(','),
      qualis: proveList.value.map((p) => {
        return {
          ...p,
          files: p.files.map((f) => f.id)
        }
      })
    }
    await EnterprisesApi.createEnterprises(data)
  }
}

const setProve = (prove) => {
  proveList.value.push(prove)
}

getSelectOption()
onMounted(() => {})
</script>

<style lang="scss" scoped>
.view-wrapper {
  display: flex;
  flex-flow: row nowrap;
  gap: 40px;
  .title-wrapper {
    font-size: 16px;
    line-height: 140%;
    font-weight: 700;
    margin-bottom: 40px;
  }
  .form-photo {
    grid-column: span 2;
  }
  .base-form {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 40px;
    .el-form-item--large {
      margin-bottom: 0;
    }
    .form-textarea {
      grid-row: span 2;
      ::v-deep(.el-textarea) {
        height: 100%;
        .el-textarea__inner {
          height: 100%;
          white-space: pre-wrap;
          &::-webkit-scrollbar {
            width: 4px;
          }
          &::-webkit-scrollbar-thumb {
            background-color: #ccc;
            border-radius: 10px;
          }
          &::-webkit-scrollbar-track {
            background-color: transparent;
          }
          &::-webkit-scrollbar-button {
            display: none;
            height: 2px;
          }
        }
      }
    }
    .form-sub-title {
      font-size: 16px;
      line-height: 140%;
      font-weight: 700;
      grid-column: span 2;
    }

    :deep(
      .el-input-number.is-controls-right[class*='large'] [class*='decrease'],
      .el-input-number.is-controls-right[class*='large'] [class*='increase']
    ) {
      --el-input-number-controls-height: 50%;
    }
    :deep(.el-input__suffix-inner > :first-child) {
      margin-right: 8px;
    }
  }
  .prove-wrapper {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    .prove {
      width: 200px;
      height: 238px;
      border: 1px solid #ccc;
      border-radius: 8px;
      overflow: hidden;
      padding: 12px;
    }
    .add-prove {
      width: 200px;
      height: 238px;
      border: 1px dashed #ccc;
      border-radius: 8px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #ccc;
      transition: all 0.2s;
      &:hover {
        color: var(--el-color-primary);
        border-color: var(--el-color-primary);
        cursor: pointer;
      }
    }
  }
}
</style>
