<template>  
  <div>
    <el-dialog
      v-model="state.showDialog"
      destroy-on-close
      :title="title"
      draggable
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="769px"
    >
      <el-form ref="formRef" :model="form" size="default" label-width="80px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="" prop="logo" :rules="[{ required: true, message: '请上传项目图标', trigger: ['blur', 'change'] }]">
                <el-upload class="avatar-uploader"
                ref="uploadRef" 
                :data="{ fileDirectory: state.fileDirectory }"
                :action="uploadAction"  
                :headers="uploadHeaders"
                :show-file-list="false" 
                :on-success="onSuccess"
            :on-error="onError">
                  <img v-if="form.logo" :src="form.logo" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="项目名称" prop="name" :rules="[{ required: true, message: '请输入项目名称', trigger: ['blur', 'change'] }]">
              <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="结算周期" prop="code" :rules="[{ required: true, message: '请输入结算周期', trigger: ['blur', 'change'] }]">
              <el-input v-model="form.code" autocomplete="off" />
            </el-form-item>
          </el-col>          
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="最高佣金" prop="realName" :rules="[{ required: true, message: '请输入最高佣金', trigger: ['blur', 'change'] }]">
              <el-input v-model="form.realName" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="项目简介" prop="realName" :rules="[{ required: true, message: '请输入最高佣金', trigger: ['blur', 'change'] }]">
                <el-input v-model="form.description" clearable type="textarea" />
              </el-form-item>
          </el-col>          
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="项目价格" prop="realName" :rules="[{ required: true, message: '请输入最高佣金', trigger: ['blur', 'change'] }]">
                <el-form :inline="true" ref="formPrice" :model="state.formPrice" class="demo-form-inline">
                    <el-form-item label="结算标准">
                      <el-input v-model="state.formPrice.name"></el-input>
                    </el-form-item>
                    <el-form-item label="价格">
                        <el-input v-model="state.formPrice.price"></el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary">添加</el-button>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="" prop="realName" :rules="[{ required: true, message: '请输入最高佣金', trigger: ['blur', 'change'] }]">
                  <el-table :data="state.form.prices" row-key="id" height="'100%'" style="width: 100%; height: 100%">
                <el-table-column type="index" width="80" label="序号"></el-table-column>                                
                <el-table-column prop="name" label="结算标准" min-width="140" show-overflow-tooltip/>                  
                <el-table-column prop="price" label="价格" width="100" show-overflow-tooltip/>                
                <!-- <el-table-column label="操作" width="140" header-align="center" align="center" fixed="right">
                    <template #default="{ row }">
                        <el-button v-auth="'api:admin:tenant:update'" icon="ele-EditPen" size="small" text type="primary"                            
                            >删除</el-button>                        
                    </template>
                </el-table-column> -->
            </el-table>
              </el-form-item>
            
          </el-col>


                        

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="项目详情">
              <el-input v-model="form.description" clearable type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSure" size="default" :loading="state.sureLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="admin/project/form">
import { reactive, toRefs, getCurrentInstance, ref, computed } from 'vue'
import { ProjectAddInput, TenantUpdateInput } from '/@/api/admin/data-contracts'
import { ProjectApi } from '/@/api/admin/project'
 import type { UploadInstance, UploadProps, UploadFile } from 'element-plus'
import eventBus from '/@/utils/mitt'
import { ElMessage } from 'element-plus'
import { useUserInfo } from '/@/stores/userInfo'

const storesUserInfo = useUserInfo()

const uploadRef = ref<UploadInstance>()

defineProps({
  title: {
    type: String,
    default: '',
  },
})

const { proxy } = getCurrentInstance() as any

const formRef = ref()
const state = reactive({  
  showDialog: false,
  sureLoading: false,  
  form: {} as ProjectAddInput & TenantUpdateInput,
  fileList: [] as UploadFile[],
  fileDirectory:'project',
  token: storesUserInfo.getToken(),
  formPrice: {
    name: "",
    price:""
  }
})
const { form } = toRefs(state)

// const getPkgs = async () => {
//   const res = await new PkgApi().getList().catch(() => {
//     state.pkgData = []
//   })

//   state.pkgData = res?.data ?? []
// }

// 打开对话框
const open = async (row: any = {}) => {
  // await getPkgs()

  if (row.id > 0) {
    const res = await new ProjectApi().get({ id: row.id }, { loading: true }).catch(() => {
      proxy.$modal.closeLoading()
    })

    if (res?.success) {
      state.form = res.data as ProjectAddInput & TenantUpdateInput
    }
  } else {
    state.form = { pkgIds: [] as number[], enabled: true } as ProjectAddInput & TenantUpdateInput
  }
  state.showDialog = true
}

// //手机号失去焦点
// const onBlurMobile = () => {
//   if (!state.form.userName && state.form.phone && isMobile(state.form.phone)) {
//     state.form.userName = state.form.phone
//   }
// }

// 取消
const onCancel = () => {
  state.showDialog = false
}

// 确定
const onSure = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    state.sureLoading = true
    let res = {} as any
    if (state.form.id != undefined && state.form.id > 0) {
      res = await new ProjectApi().update(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    } else {
      res = await new ProjectApi().add(state.form, { showSuccessMessage: true }).catch(() => {
        state.sureLoading = false
      })
    }
    state.sureLoading = false

    if (res?.success) {
      eventBus.emit('refreshTenant')
      state.showDialog = false
    }
  })
}

const uploadAction = computed(() => {
  return import.meta.env.VITE_API_URL + '/api/admin/file/upload-file'
})
const uploadHeaders = computed(() => {
  return { Authorization: 'Bearer ' + state.token }
})
// 上传成功
const onSuccess: UploadProps['onSuccess'] = (response) => {  
  if (response?.success) {
    state.form.logo = response.data.linkUrl;
  }
}
//上传失败
const onError: UploadProps['onError'] = (error) => {
  let message = ''
  if (error.message) {
    try {
      message = JSON.parse(error.message)?.msg
    } catch (err) {
      message = error.message || ''
    }
  }
  if (message)
    ElMessage({
      message: message,
      type: 'error',
    })
}
//
// const cellEdit = (row, colum, cell, event) => {
//   state.showDialog = false
// }

// const changeData=(value) =>{
//   const reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g
//   if (!reg.test(value.kpi.value)) {
//     return this.$message.error('只能输入数字')
//   } else if (value.kpi.value > 1000000000) {
//     return this.$message.error('输入数字过大')
//   }
//   let params = {
//     feeKpi: value.kpi.value,
//     meetingId: value.id.value,
//     paperKpi: 0,
//     registerKpi: 0,
//     viewKpi: 0,
//     type: 1
//   };
//   let { data } = await setUpMeeting(params);
//   if (data.code == 0) {
//     // this.$message.success('设置成功');
//     value.kpi.edit = false;
//   }
// }    

defineExpose({
  open,
})
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}</style>