<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="titleName"
    width="50%"
    :close-on-click-modal="false"
    :before-close="() => $emit('update:editDialog', false)">
    <el-form
      :inline="true"
      size="mini"
      :rules="editRules"
      :model="editForm"
      ref="editFormRef"
      label-width="120px">
      <div class="form-center">
        <h3>基础信息</h3>
        <div class="grid-from">
          <el-form-item label="公司名称" prop="companyName">
            <el-input
              style="width: 250px"
              v-model="editForm.companyName"
              placeholder="请输入公司名称"></el-input>
          </el-form-item>
          <el-form-item label="所属行业" prop="industry">
            <el-input
              style="width: 250px"
              v-model="editForm.industry"
              placeholder="请输入所属行业"></el-input>
          </el-form-item>
        </div>
        <div class="grid-from">
          <el-form-item label="注册地址" prop="registeredAddress">
            <el-input
              style="width: 250px"
              v-model="editForm.registeredAddress"
              clearable
              placeholder="请输入注册地址"></el-input>
          </el-form-item>
          <el-form-item label="办公地址" prop="officeAddress">
            <el-input
              style="width: 250px"
              v-model="editForm.officeAddress"
              clearable
              placeholder="请输入办公地址"></el-input>
          </el-form-item>
        </div>
        <div class="grid-from">
          <el-form-item label="业务对接人" prop="contactUserName">
            <el-input
              style="width: 250px"
              v-model="editForm.contactUserName"
              clearable
              placeholder="请输入业务对接人"></el-input>
          </el-form-item>
          <el-form-item label="对接人职位" prop="contactUserTitle">
            <el-input
              style="width: 250px"
              v-model="editForm.contactUserTitle"
              clearable
              placeholder="请输入对接人职位"></el-input>
          </el-form-item>
        </div>
        <div class="grid-from">
          <el-form-item label="对接人电话" prop="contactUserPhone">
            <el-input
              style="width: 250px"
              v-model="editForm.contactUserPhone"
              clearable
              placeholder="请输入对接人电话"></el-input>
          </el-form-item>
          <el-form-item label="对接人邮箱" prop="contactUserEmail">
            <el-input
              style="width: 250px"
              v-model="editForm.contactUserEmail"
              clearable
              placeholder="请输入对接人邮箱"></el-input>
          </el-form-item>
        </div>
        <div class="grid-from">
          <el-form-item label="客户运营" prop="operationUserId">
            <el-select
              v-model="editForm.operationUserId"
              placeholder="请选择客户运营"
              style="width: 250px"
              filterable
              clearable>
              <el-option
                v-for="item in userLists"
                :key="item.id"
                :label="item.realName"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="grid-from">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="editForm.remark"
              clearable
              style="width: 250px"
              :rows="2"
              type="textarea"
              placeholder="请输入备注" />
          </el-form-item>
          <el-form-item label="营业执照" prop="businessLicenseUri">
            <div class="my-flex-1">
              <upload-images
                ref="uploadRef"
                sortField="sort"
                businessType="other"
                uploadApiUrl="upload/oss"
                :type="limitFileType"
                :isFloat="false"
                :width="250"
                :hasWidth="true"
                :hasOss="true"
                :length="1"
                v-model="businessLicenseFileList"
                @selectImg="selectImg"
                @remove="onImgRemove"></upload-images>
            </div>
          </el-form-item>
        </div>
      </div>
      <div class="form-center" v-if="isFullValidate">
        <h3>ERP信息</h3>
        <div class="grid-from">
          <el-form-item label="域名" prop="domain">
            <el-input
              style="width: 250px"
              v-model.trim="editForm.domain"
              clearable
              :disabled="
                ['已开通', '开通失败', '已关闭'].includes(erpStatus) &&
                commandTitle === 'edit'
              "
              placeholder="请输入域名"
              @change="onDomainChange">
              <template slot="append">.jomalls.com</template>
            </el-input>
          </el-form-item>
          <el-form-item label="套餐" prop="packages">
            <el-select
              style="width: 250px"
              v-model="editForm.packages"
              size="small"
              @change="changeCharges"
              placeholder="请选择套餐">
              <el-option
                v-for="item in paymentPackages"
                :key="item.id"
                :value="item.key"
                :label="item.name"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="grid-from">
          <el-form-item label="资费" prop="charges">
            <el-input
              style="width: 250px"
              v-model="editForm.charges"
              disabled
              clearable
              placeholder="请输入资费"></el-input>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <span slot="footer">
      <el-button size="mini" @click="$emit('update:editDialog', false)">
        取 消
      </el-button>
      <el-button size="mini" type="primary" @click="onSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import UploadImages from '@/components/base/image-list.vue'
const TITLE_MAP = {
  add: '新增客户',
  openErp: '开通ERP',
  edit: '编辑'
}
export default {
  data() {
    return {
      limitFileType: ['jpg', 'png'],
      paymentPackages: [
        {
          id: 0,
          cny: 'CNY',
          price: 10,
          name: '内测版',
          key: 'INNERBATE',
          o: 0.2,
          oName: '0',
          orders: 10000
        },
        {
          id: 1,
          cny: 'CNY',
          price: 10000,
          name: '基础版',
          key: 'PAYBASE',
          o: 0.2,
          oName: '0.2元/单',
          orders: 50000
        },
        {
          id: 2,
          cny: 'CNY',
          price: 30000,
          name: '进阶版',
          key: 'PAYADVANCED',
          o: 0.16,
          oName: '0.16元/单',
          orders: 187500
        },
        {
          id: 3,
          cny: 'CNY',
          price: 9800,
          p: 9800,
          name: '尊享版',
          key: 'PAYXVCVT',
          month: 1,
          oName: '9800元/月',
          m: '按月收费'
        },
        {
          id: 4,
          cny: 'CNY',
          price: 29800,
          p: 29800,
          name: '至尊版',
          key: 'PAYULTIMATE',
          month: 1,
          oName: '29800元/月',
          m: '按月收费'
        }
      ]
    }
  },
  components: {
    UploadImages
  },
  props: {
    editForm: {
      type: Object,
      default: () => ({})
    },
    editDialog: {
      type: Boolean,
      default: false
    },
    commandTitle: {
      type: String,
      default: ''
    },
    erpStatus: {
      type: String,
      default: ''
    },
    userLists: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.editDialog
      },
      set(val) {
        this.$emit('update:editDialog', val)
      }
    },
    titleName() {
      return TITLE_MAP[this.commandTitle] || ''
    },
    // 开通ERP|编辑时 + ERP服务是已开通、开通失败和已关闭时，全部必填,出现ERP信息表单
    // 新增客户|编辑 + ERP服务是未开通时，只校验必填项,不出现ERP信息表单
    isFullValidate() {
      return (
        this.commandTitle === 'openErp' ||
        (this.erpStatus !== '未开通' && this.commandTitle !== 'add')
      )
    },
    editRules() {
      const requiredRule = (message, trigger = 'blur') => [
        { required: true, message, trigger }
      ]
      // 仅"业务对接人"、"公司名称"必填
      const baseRules = {
        companyName: requiredRule('请输入公司名称'),
        contactUserName: requiredRule('请输入业务对接人')
      }
      // 其他情况：维持原有全部必填
      if (this.isFullValidate) {
        return {
          companyName: requiredRule('请输入公司名称'),
          officeAddress: requiredRule('请输入办公地址'),
          contactUserName: requiredRule('请输入业务对接人'),
          contactUserTitle: requiredRule('请输入对接人职位'),
          contactUserPhone: requiredRule('请输入对接人电话'),
          contactUserEmail: requiredRule('请输入对接人邮箱'),
          businessLicenseUri: requiredRule('请上传营业执照', 'change'),
          domain: requiredRule('请输入域名'),
          packages: requiredRule('请输入套餐'),
          charges: requiredRule('请输入资费')
        }
      }
      return baseRules
    },
    // 把 editForm.businessLicenseUri(逗号分隔字符串) 与上传组件所需的数组双向桥接
    businessLicenseFileList: {
      get() {
        const uri = this.editForm.businessLicenseUri
        if (!uri) return []
        return String(uri)
          .split(',')
          .map((u) => u.trim())
          .filter((u) => !!u)
          .map((url, index) => ({
            imagePath: url,
            sort: index + 1,
            type: ''
          }))
      },
      set(val) {
        const list = Array.isArray(val) ? val : []
        const imagePath = list
          .map((ee) => ee.imagePath || '')
          .filter(Boolean)
          .join(',')
        this.$set(this.editForm, 'businessLicenseUri', imagePath)
      }
    }
  },
  methods: {
    onDomainChange(e) {
      this.$set(this.editForm, 'apiName', e)
      this.$set(this.editForm, 'databaseName', 'saas_' + e)
    },
    open() {
      // 弹窗打开时，若套餐为空则默认为基础版；编辑场景下保留已有套餐
      if (!this.editForm.packages) {
        this.$set(this.editForm, 'packages', 'PAYBASE')
      }
    },
    changeCharges(v) {
      if (!v) return
      const charges = this.paymentPackages.find((item) => item.key === v)
      if (charges) {
        this.$set(this.editForm, 'charges', charges.oName)
      }
    },
    // 上传/重排后同步到 editForm.businessLicenseUri（v-model change 已自动同步，这里再做一次防御性赋值）
    selectImg(file) {
      const list = Array.isArray(file) ? file : []
      const imagePath = list
        .map((ee) => ee.imagePath || '')
        .filter(Boolean)
        .join(',')
      this.$set(this.editForm, 'businessLicenseUri', imagePath)
    },
    // 删除图片：上传组件 splice 后不会 emit change，从组件读取当前 fileList 并手动同步
    onImgRemove() {
      this.$nextTick(() => {
        const ref = this.$refs.uploadRef
        const fileList = ref && Array.isArray(ref.fileList) ? ref.fileList : []
        const imagePath = fileList
          .map((ee) => ee.imagePath || '')
          .filter(Boolean)
          .join(',')
        this.$set(this.editForm, 'businessLicenseUri', imagePath)
      })
    },
    handleClose() {
      this.dialogVisible = false
    },
    async onSubmit() {
      try {
        if (!(await this.$refs.editFormRef.validate())) return
      } catch {
        return
      }
      this.$emit('onSubmit', this.editForm)
    },
    clearForm() {
      this.$refs.editFormRef?.clearValidate()
    }
  }
}
</script>
<style scoped lang="scss">
// 表单整体
.el-form {
  :deep(.el-form-item__content) {
    align-items: baseline !important;
  }
  :deep(.el-form-item) {
    margin-bottom: 16px;

    .el-form-item__label {
      font-size: 13px;
      color: #606266;
      font-weight: 500;
    }

    // 禁用输入框视觉处理
    :deep(.el-input.is-disabled .el-input__wrapper),
    :deep(.el-textarea.is-disabled .el-textarea__inner),
    :deep(.el-date-editor.is-disabled) {
      background-color: #f5f7fa !important;
      box-shadow: 0 0 0 1px #e4e7ed inset !important;
    }
  }
}
.form-center {
  background: #fff;
  border-radius: 8px;
  padding: 18px 20px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
  border: 1px solid #ebeef5;
  transition: box-shadow 0.2s ease;

  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }

  &:last-child {
    margin-bottom: 0;
  }

  h3 {
    margin: 0 0 14px;
    padding-left: 10px;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    line-height: 1.4;
    border-left: 3px solid #409eff;
  }

  .grid-from {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px 20px;
  }
}
</style>
