<template>
  <div>
    <!-- 增改查弹窗 -->
    <el-dialog :title="titles[mode] || '详情'" :visible.sync="formVisible" class="card-edit-dialog" :class="mode" width="860px" append-to-body :close-on-click-modal="false">
      <el-form ref="detailForm" v-loading="detailLoading" :model="formData" :rules="rules" label-position="right" label-width="150px">
        <el-form-item label="企业名称：" prop="name" class="full-width">
          <el-input v-if="isEditAdd" v-model.trim="formData.name" placeholder="请输入企业名称" clearable maxlength="50" />
          <span v-else>{{ formData.name }}</span>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码：" prop="creditCode">
              <el-input v-if="isEditAdd" v-model.trim="formData.creditCode" placeholder="请输入统一社会信用代码" clearable maxlength="50" />
              <span v-else>{{ formData.creditCode }}</span>
            </el-form-item>
            <el-form-item label="法人：" prop="legalName">
              <el-input v-if="isEditAdd" v-model.trim="formData.legalName" placeholder="请输入法人" clearable maxlength="16" />
              <span v-else>{{ formData.legalName }}</span>
            </el-form-item>
            <el-form-item label="联系人：" prop="contactName">
              <el-input v-model.trim="formData.contactName" placeholder="请输入联系人" clearable maxlength="16" />
            </el-form-item>
            <el-form-item label="邮编：" prop="zipCode">
              <el-input v-model.trim="formData.zipCode" placeholder="请输入邮编" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业账号：" prop="userName" label-width="120px">
              <el-input
                v-if="isEditAdd"
                v-model.trim="formData.userName"
                :disabled="mode !== 'add'"
                placeholder="请输入6~16位数字、字母"
                clearable
                maxlength="16"
              />
              <span v-else>{{ formData.userName }}</span>
            </el-form-item>
            <el-form-item label="法人手机号：" prop="legalMobile" label-width="120px">
              <el-input v-model.trim="formData.legalMobile" placeholder="请输入法人手机号" clearable maxlength="11" />
            </el-form-item>
            <el-form-item label="联系人手机号：" prop="contactMobile" label-width="120px">
              <el-input v-model.trim="formData.contactMobile" placeholder="请输入联系人手机号" clearable maxlength="11" />
            </el-form-item>
            <el-form-item label="邮箱：" prop="email" label-width="120px">
              <el-input v-model.trim="formData.email" placeholder="请输入邮箱" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="地址：" class="address">
            <el-col v-if="isEditAdd" :span="9">
              <el-form-item prop="areaArr">
                <el-cascader
                  ref="areaArr"
                  v-model.trim="formData.areaArr"
                  :options="global.regionTree"
                  :props="{ expandTrigger: 'click', value: 'id', label: 'name', children: 'children' }"
                  clearable
                  filterable
                  :show-all-levels="true"
                  placeholder="请选择城市"
                />
              </el-form-item>
            </el-col>
            <el-col v-if="isEditAdd" :span="14" :offset="1">
              <el-form-item prop="address">
                <el-input v-model.trim="formData.address" placeholder="请输入详细地址" clearable maxlength="50" />
              </el-form-item>
            </el-col>
            <span v-else>{{ formData.fullAddress }}</span>
          </el-form-item>
        </el-row>
        <el-form-item prop="remark" label="备注：" class="full-width">
          <el-input
            v-model.trim="formData.remark"
            :rows="4"
            resize="none"
            show-word-limit
            maxlength="100"
            type="textarea"
            clearable
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="登录时短信验证：" prop="isSms">
              <el-switch v-model.trim="formData.isSms" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色：" prop="roleIds" label-width="120px">
              <el-select v-model="formData.roleIds" placeholder="请选择角色" clearable filterable multiple collapse-tags>
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="detailLoading" @click="formVisible = false">关闭</el-button>
        <el-button v-if="isEditAdd" type="primary" :loading="detailLoading" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addCompany, getCompany, updateCompany } from '@/apiV2/company'
import { roleCompanyList } from '@/apiV2/role'
import { deepClone } from '@/utils'
import { phoneReg } from '@/utils/validate'
import { genNameValidator, genUserNameValidator } from '@/utils/validator'

const defaultFormData = {
  name: '',
  creditCode: '',
  legalName: '',
  contactName: '',
  zipCode: '',
  userName: '',
  legalMobile: '',
  contactMobile: '',
  email: '',
  areaArr: [],
  province: '',
  city: '',
  county: '',
  address: '',
  isSms: 0,
  roleIds: []
}

export default {
  name: '',
  inject: ['global', 'refresh'],
  data() {
    return {
      detailLoading: false,
      mode: 'see', // 查看see / 编辑edit / 添加add
      titles: { // 弹窗标题(动态)
        see: '查看',
        add: '新增',
        edit: '编辑'
      },
      formVisible: false, // 弹窗显示
      formConfig: {}, // 表单配置
      formData: { ...defaultFormData }, // 表单数据
      roleList: [], // 角色列表
      rules: {
        name: [
          { required: true, message: '企业名称不能为空', trigger: 'change' },
          { validator: genNameValidator([2, 50]), trigger: 'change' }
        ],
        creditCode: [
          // { required: true, message: '统一社会信用代码不能为空', trigger: 'change' },
          { validator: genUserNameValidator([2, 50]), trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '企业账号不能为空', trigger: 'change' },
          { validator: genUserNameValidator([5, 16]), trigger: 'blur' }
        ],
        contactName: [
          { required: true, message: '联系人不能为空', trigger: 'change' },
          { validator: genNameValidator([2, 16]), trigger: 'blur' }
        ],
        legalName: [
          // { required: true, message: '法人不能为空', trigger: 'change' },
          { validator: genNameValidator([2, 16]), trigger: 'change' }
        ],
        legalMobile: [
          { pattern: phoneReg, message: '法人手机号限制11个字符，且为以1开头的数', trigger: 'blur' }
        ],
        contactMobile: [
          { required: true, message: '联系人手机号不能为空', trigger: 'change' },
          { pattern: phoneReg, message: '联系人手机号限制11个字符，且为以1开头的数', trigger: 'blur' }
        ],
        email: [
          // { required: true, message: '邮箱不能为空', trigger: 'change' },
          {
            pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: '请输入正确的邮箱地址，例如：“user@example.com”',
            trigger: 'blur'
          }
        ],
        areaArr: [
          // { required: true, message: '城市不能为空', trigger: 'change' }
        ],
        address: [
          // { required: true, message: '详细地址不能为空', trigger: 'change' }
        ],
        zipCode: [
          { pattern: /\d{6}/, message: '请输入正确的邮编', trigger: 'change' }
        ],
        roleIds: [
          { required: true, message: '角色不能为空', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    isEditAdd() {
      return this.mode === 'edit' || this.mode === 'add'
    }
  },
  methods: {
    showDialog({ mode, formConfig, formData, formTitle }) {
      this.mode = mode || (this.formData.id ? 'edit' : 'add')
      if (this.mode === 'add') {
        this.formData = { ...defaultFormData }
      } else {
        this.formData = { ...formData }
      }
      this.initFormData()
      this.getRoleList()
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.detailForm.clearValidate()
      })
    },
    async initFormData() { // 表单数据初始化
      const { id, province, city, county } = this.formData
      if (this.mode === 'edit') {
        this.detailLoading = true
        try {
          const { success, data } = await getCompany(id)
          if (success) {
            Object.assign(this.formData, data)
          }
        } finally {
          this.detailLoading = false
        }
      }
      this.$set(this.formData, 'areaArr', [province, city, county].filter(i => i).map(i => Number(i)))
    },
    async getRoleList() { // 获取角色列表
      try {
        const { success, data } = await roleCompanyList()
        if (success) {
          this.roleList = data || []
        }
      } catch (error) {
        console.error('获取角色列表失败:', error)
      }
    },
    filterFormData(formData) { // 提交数据过滤
      const data = deepClone(formData)
      const [province, city, county] = data['areaArr']
      Object.assign(data, { province, city, county })
      return data
    },
    submit() {
      this.$refs.detailForm.validate(async(valid) => {
        if (valid) {
          const formData = this.filterFormData(this.formData)
          console.log('FORM', formData)
          this.detailLoading = true
          try {
            let res = {}
            if (this.mode === 'add') {
              res = await addCompany(formData, false)
            } else {
              res = await updateCompany(formData)
            }
            if (res.success) {
              this.formVisible = false
              this.refresh()
              if (this.mode === 'add') { // 新增成功弹窗
                const txt = `
                <p class="delText">企业创建成功！</p>
                ${res.data ? `<p class="delText">企业账号初始密码为：${res.data}</p>` : ''}
                `
                await this.$confirm(txt, '温馨提示', {
                  dangerouslyUseHTMLString: true,
                  type: 'success',
                  showCancelButton: false,
                  confirmButtonText: '我知道了'
                })
              }
            }
          } finally {
            this.detailLoading = false
          }
        } else {
          // this.$message.warning('校验失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">

.address {
  padding-top: 5px;
  padding-bottom: 5px;
  width: 100%;
  /deep/ .el-cascader {
  }
}

.card-edit-dialog {
  padding: 0px;
  .el-input {
    // width: 280px;
  }
  /deep/ .el-form-item {
    &.full-width {
      // width: 100%;
      .el-form-item__content {
        max-width: none;
      }
    }
    .el-form-item__content {
      .el-cascader {
        // width: 100%;
      }
    }
  }
}

.width-clear {
  width: auto
}

</style>
