<template>
  <div class="edit-company">
    <div class="container">
      <div class="content">
        <div class="title">{{ state.isAdd ? '公司信息' : '编辑公司信息' }}</div>
        <el-form
          ref="formRef"
          :model="state.form"
          :rules="state.rules"
          hide-required-asterisk
          label-width="90px"
          label-position="left"
        >
          <el-form-item label="公司LOGO" class="flx-align-center" prop="FLogo">
            <el-upload
              class="avatar-uploader"
              action="/K3Cloud/LQKJ.K3.NSJYBSystem.WebApi.WebApiEditService.UploadFile,LQKJ.K3.NSJYBSystem.WebApi.common.kdsvc"
              name="File"
              accept="image/*"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :disabled="!state.isAdd"
            >
              <img
                v-if="state.form.FLogo"
                :src="baseURL + '/' + state.imgUrl"
                class="avatar"
                width="56"
                height="56"
              />
              <el-icon v-else class="avatar-uploader-icon"><i-ep-Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="公司名称">
            <span>{{ state.isAdd ? state.form.FName : userInfoStore.companyInfo?.FNAME }}</span>
          </el-form-item>
          <el-form-item label="公司类型" prop="FIndustry">
            <div class="flx-direction-column">
              <div
                class="info-collapse flx-justify-between"
                @click="state.tradeAcive = !state.tradeAcive"
              >
                <div>{{ filterName(state.informationData?.Trade, state.form.FIndustry) }}</div>
                <el-icon v-show="state.tradeAcive"><i-ep-CaretTop /></el-icon>
                <el-icon v-show="!state.tradeAcive"><i-ep-CaretBottom /></el-icon>
              </div>
              <div v-show="state.tradeAcive" class="info-list">
                <span
                  v-for="item in state.informationData?.Trade"
                  :key="item.FNUMBER"
                  :style="{
                    color: state.form.FIndustry === item.FNUMBER ? '#177CFA !important' : '',
                    cursor: !state.isAdd ? 'no-drop' : ''
                  }"
                  :class="state.isAdd ? '' : 'disabled-hover'"
                  @click="handleChange('Trade', item.FNUMBER)"
                  >{{ item.FDATAVALUE }}</span
                >
              </div>
            </div>
          </el-form-item>
          <el-form-item label="公司规模" prop="FScaleS">
            <div class="flx-direction-column">
              <div
                class="info-collapse flx-justify-between"
                @click="state.memberAcive = !state.memberAcive"
              >
                <div>{{ filterName(state.informationData?.Member, state.form.FScaleS) }}</div>
                <el-icon v-show="state.memberAcive"><i-ep-CaretTop /></el-icon>
                <el-icon v-show="!state.memberAcive"><i-ep-CaretBottom /></el-icon>
              </div>
              <div v-show="state.memberAcive" class="info-list">
                <span
                  v-for="item in state.informationData?.Member"
                  :key="item.FNUMBER"
                  :style="{ color: state.form.FScaleS === item.FNUMBER ? '#177CFA ' : '' }"
                  @click="handleChange('Member', item.FNUMBER)"
                  >{{ item.FDATAVALUE }}</span
                >
              </div>
            </div>
          </el-form-item>
          <el-form-item label="融资情况" prop="FFinancingS">
            <div class="flx-direction-column">
              <div
                class="info-collapse flx-justify-between"
                @click="state.financingAcive = !state.financingAcive"
              >
                <div>
                  {{ filterName(state.informationData?.Financing, state.form.FFinancingS) }}
                </div>
                <el-icon v-show="state.financingAcive"><i-ep-CaretTop /></el-icon>
                <el-icon v-show="!state.financingAcive"><i-ep-CaretBottom /></el-icon>
              </div>
              <div v-show="state.financingAcive" class="info-list">
                <span
                  v-for="item in state.informationData?.Financing"
                  :key="item.FNUMBER"
                  :style="{ color: state.form.FFinancingS === item.FNUMBER ? '#177CFA' : '' }"
                  @click="handleChange('Financing', item.FNUMBER)"
                  >{{ item.FDATAVALUE }}</span
                >
              </div>
            </div>
          </el-form-item>
          <el-form-item label="所在街道办" prop="FSubstreet">
            <div class="flx-direction-column">
              <div
                class="info-collapse flx-justify-between"
                @click="state.streetAcive = !state.streetAcive"
              >
                <div>{{ filterName(state.streetList, state.form.FSubstreet) }}</div>
                <el-icon v-show="state.streetAcive"><i-ep-CaretTop /></el-icon>
                <el-icon v-show="!state.streetAcive"><i-ep-CaretBottom /></el-icon>
              </div>
              <div v-show="state.streetAcive" class="info-list">
                <span
                  v-for="item in state.streetList"
                  :key="item.FNUMBER"
                  :style="{
                    color: state.form.FSubstreet === item.FNUMBER ? '#177CFA !important' : '',
                    cursor: !state.isAdd ? 'no-drop' : ''
                  }"
                  :class="state.isAdd ? '' : 'disabled-hover'"
                  @click="handleChange('Street', item.FNUMBER)"
                  >{{ item.FNAME }}</span
                >
              </div>
            </div>
          </el-form-item>
          <el-form-item label="工商信息">
            <businessInfo ref="businessInfoRef" :disabled="!state.isAdd" />
          </el-form-item>
          <el-form-item label="公司地址" prop="FAddresss">
            <el-input v-model="state.form.FAddresss" placeholder="请填写真实有效的公司地址" />
          </el-form-item>
          <el-form-item label="公司福利" prop="FCorporateWelfare">
            <el-input
              v-model="state.form.FCorporateWelfare"
              placeholder="请输入公司福利多个福利请用逗号隔开"
            />
          </el-form-item>
          <el-form-item label="公司介绍" prop="">
            <el-input v-model="state.form.FCompanyProfile" type="textarea" :rows="4" />
          </el-form-item>
        </el-form>
      </div>
      <div class="confirm">
        <span v-show="!state.isAdd" @click="submit">确定</span>
        <span v-show="state.isAdd" @click="submit">提交审核</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getInformation } from '@/services/api/common'
import { getAdminCompanyInfo, editCompanyInfo } from '@/services/api/recruitmentManagement'
import { getStreet } from '@/services/api/streetOfficeSpecialTopic'
import { enterpriseRegisters } from '@/services/api/login'
import { baseURL } from '@/services'
import { useUserInfoStore } from '@/stores/modules/userInfo'
import businessInfo from './components/businessInfo.vue'

const route = useRoute()
const router = useRouter()
const userInfoStore = useUserInfoStore()

const formRef = ref()
const businessInfoRef = ref()
const state = reactive({
  form: {
    FName: '', //公司名称
    FLogo: '', //logo
    FUserPhone: '', //注册手机号
    FAddresss: '', //公司地址
    FIndustry: '', // 公司类型
    FFinancingS: '', // 融资情况
    FScaleS: '', // 公司规模
    FCompanyProfile: '', // 公司介绍
    FSubstreet: '', // 所属街道
    FCorporateWelfare: '' //公司福利
  } as any,
  rules: {
    FLogo: [{ required: true, message: '请上传公司 logo', trigger: 'change' }],
    FAddresss: [{ required: true, message: '请选择公司地址', trigger: 'blur' }],
    FIndustry: [{ required: true, message: '请选择公司类型', trigger: 'blur' }],
    FFinancingS: [{ required: true, message: '请选择融资情况', trigger: 'blur' }],
    FScaleS: [{ required: true, message: '请输选择公司规模', trigger: 'blur' }],
    FCompanyProfile: [{ required: true, message: '请输入公司介绍', trigger: 'blur' }],
    FSubstreet: [{ required: true, message: '请选择所属街道', trigger: 'blur' }],
    FCorporateWelfare: [{ required: true, message: '请输入公司福利', trigger: 'blur' }]
  },
  Parmeter: {
    IsDeleteEntry: 'true',
    Model: {
      FName: '', //公司名称
      FLogo: '', //logo
      FUserPhone: '', //注册手机号
      FAddresss: '', //地址
      FIndustry: {
        //公司类型
        FNumber: ''
      },
      FFinancingS: {
        //融资情况
        FNumber: ''
      },
      FScaleS: {
        //公司规模
        FNumber: ''
      },
      FCompanyProfile: '', //公司介绍
      FSubstreet: {
        //所属街道
        FNUMBER: ''
      },
      FCorporateWelfare: '', //公司福利
      FCompanyName: '', //公司名称
      FLegalRepresentative: '', //法定代表人
      FRegisteredAddress: '', //注册地址
      FOperatingState: '', //经营状态
      FRegisteredCapital: '', //注册资本
      FTypeEnterprise: '', //企业类型
      FOperatingTerm: '', //营业期限
      FAffiliatingArea: '', //所属地区
      FCreditCode: '', //统一社会信用代码
      FDateApproval: '', //核准日期
      FRegistrationAuthority: '', //登记机关
      FDateEstablishment: '', //成立日期
      FPreviouslyName: '', //曾用名
      FFIndustryGS: '', //所属行业
      FBusinessScope: '', //经营范围
      F_LQKJ_EnterpriseUserEntity: [
        {
          FEntryID: 0,
          FUserPhoneS: '', //注册手机号
          FUserName: '先生/女士',
          FJobTitle: '总经理'
        }
      ]
    }
  },
  informationData: {} as any,
  streetList: [] as any,
  imgUrl: '',
  tradeAcive: false,
  memberAcive: false,
  financingAcive: false,
  streetAcive: false,
  companyType: '',
  isAdd: false
})

const handleAvatarSuccess = (res: any) => {
  state.form.FLogo = res.data.FileId
  state.imgUrl = res.data.Url
}

const filterName = (list: any[] = [], FNUMBER: string) => {
  let row: any = list?.find((item: any) => item.FNUMBER === FNUMBER)
  return row ? (row.FDATAVALUE ? row.FDATAVALUE : row.FNAME) : '请选择'
}

const submit = async () => {
  let business = true
  if (state.isAdd) business = await businessInfoRef.value?.formCheck()
  formRef.value.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      if (!business) return ElMessage.warning('请填写完整公司信息')
      ElMessageBox.confirm(`确定提交审核?`, `提交审核`, {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          if (state.isAdd) {
            let data = {
              Parmeter: {
                IsDeleteEntry: 'true',
                Model: { ...state.Parmeter.Model, ...businessInfoRef.value.form, ...state.form }
              }
            }
            data.Parmeter.Model.FIndustry = { FNumber: state.form.FIndustry }
            data.Parmeter.Model.FScaleS = { FNumber: state.form.FScaleS }
            data.Parmeter.Model.FFinancingS = { FNumber: state.form.FFinancingS }
            data.Parmeter.Model.FSubstreet = { FNUMBER: state.form.FSubstreet }
            data.Parmeter.Model.F_LQKJ_EnterpriseUserEntity[0].FUserPhoneS = state.form.FUserPhone
            const res: any = await enterpriseRegisters(data)
            if (res.code === 200) {
              ElNotification({
                title: '企业注册',
                message: res.msg,
                type: 'success'
              })
              router.back()
            }
          } else {
            let data = {
              Parmeter: {
                NeedUpDateFields: [
                  'FAddresss',
                  'FFinancingS',
                  'FScaleS',
                  'FCompanyProfile',
                  'FCorporateWelfare'
                ],
                IsDeleteEntry: 'false',
                Model: {
                  FID: 0, //无需填写
                  FAddresss: state.form.FAddresss, //地址
                  FFinancingS: {
                    //融资情况
                    FNumber: state.form.FFinancingS
                  },
                  FScaleS: {
                    //公司规模
                    FNumber: state.form.FScaleS
                  },
                  FCompanyProfile: state.form.FCompanyProfile, //公司介绍
                  FCorporateWelfare: state.form.FCorporateWelfare //公司福利
                }
              }
            }
            const res: any = await editCompanyInfo(data)
            if (res.code === 200) {
              // 编辑成功后更新内存公司信息
              userInfoStore.companyInfo.ADDRESSS = state.form.FAddresss
              userInfoStore.companyInfo.FCOMPANYPROFILE = state.form.FCompanyProfile
              userInfoStore.companyInfo.FSCALE = state.informationData?.Member.find(
                (item: any) => item.FNUMBER === state.form.FScaleS
              )?.FDATAVALUE
              userInfoStore.companyInfo.FFINANCING = state.informationData?.Financing.find(
                (item: any) => item.FNUMBER === state.form.FFinancingS
              )?.FDATAVALUE
              ElNotification({
                title: '企业编辑',
                message: res.msg,
                type: 'success'
              })
              router.back()
            }
          }
        })
        .catch(() => {})
    } else ElMessage.warning('请填写完整公司信息')
  })
}

const handleChange = async (type: string, FNUMBER: string) => {
  switch (type) {
    case 'Trade':
      if (!state.isAdd) return
      state.form.FIndustry = FNUMBER
      break
    case 'Member':
      state.form.FScaleS = FNUMBER
      break
    case 'Financing':
      state.form.FFinancingS = FNUMBER
      break
    default:
      if (!state.isAdd) return
      state.form.FSubstreet = FNUMBER
      break
  }
}

const initAdminCompanyInfo = async () => {
  const res: any = await getAdminCompanyInfo()
  if (res.code === 200) {
    businessInfoRef.value.form = res.data?.gsData
    state.imgUrl = res.data?.FLogoUrl
    state.form = { ...state.form, ...res.data }
    console.log(res)
  }
}

const init = async () => {
  const res: any = await getInformation({
    AuxiliaryS: ['EDUCATION', 'Financing', 'Member', 'Trade']
  })
  state.informationData = res.data
  const street: any = await getStreet()
  if (street.code === 200) {
    state.streetList = street.data
    state.streetList.map((item: any, i: number) => (item.FNAME = item.FNAME + '办'))
  }
}

onMounted(() => {
  const { register, companyName, phone }: any = route.query
  if (register) {
    state.isAdd = true
    state.form.FName = companyName
    state.form.FUserPhone = phone
  } else {
    initAdminCompanyInfo()
  }
  init()
})
</script>

<style lang="scss" scoped>
@import url(./style/editCompany.scss);
</style>
