<template>
  <!-- 基于 Element UI 新增和修改弹窗 -->
  <el-dialog
      :title="!dataForm.id ? '添加' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible"
      v-dialogDrag
  >
    <!-- 新增和修改表单 -->
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataSubmit()" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="供应商代码" prop="custCode">
            <el-input v-model="dataForm.custCode" placeholder="供应商代码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商名称" prop="custName">
            <el-input v-model="dataForm.custName" placeholder="供应商名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="营业执照号码" prop="licenseNumber">
            <el-input v-model="dataForm.licenseNumber" placeholder="营业执照号码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="contactWay">
            <el-input v-model="dataForm.contactWay" placeholder="联系方式"></el-input>
<!--            <el-button type="primary" size="small" style="margin-left: 10px;" @click="generateAccount">生成账号</el-button>-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="dataForm.status" placeholder="请选择状态" style="width: 100%" disabled>
              <el-option
                v-for="dict in dict.type.cust_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="dataForm.contactPerson" placeholder="联系人"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dataForm.remark" placeholder="备注" type="textarea" rows="3"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import * as api from '@/api/cmcust.js'
  export default {
    dicts: ['cust_status'],
    data () {
      return {
        visible: false,
        dataForm: {
          id: 0,
          custCode: '' ,
          custName: '' ,
          licenseNumber: '' ,
          contactWay: '' ,
          status: '0' ,
          contactPerson: '' ,
          remark: '' ,
        },
        dataRule: {
          custCode: [
            { required: true, message: '供应商代码  为必填项', trigger: 'blur' }
          ],
          custName: [
            { required: true, message: '供应商名称  为必填项', trigger: 'blur' }
          ],
        }
      }
    },
    methods: {
      init (id) { // 初始化表单验证规则
        this.dataForm.id = id || 0
        this.dataForm.status = '0' // 默认设置为待审核
        this.visible = true
        this.$nextTick(function() {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            api.cmcustDetailApi(id).then(function(res) {
              this.dataForm = res;
              this.dataForm.status = res.status || '0' // 编辑时使用现有状态，确保禁用状态下显示正确
            }.bind(this))
          }
        }.bind(this))
      },
      // 生成账号
      generateAccount() {
        if (!this.dataForm.contactWay) {
          this.$message.error('请先填写联系方式')
          return
        }
        // 检查联系方式是否有效（简单验证手机号格式）
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(this.dataForm.contactWay)) {
          this.$message.error('请输入有效的手机号码')
          return
        }
        // 生成账号和密码（使用联系方式）
        const account = this.dataForm.contactWay
        const password = this.dataForm.contactWay
        // 调用API创建用户账号
        api.cmcustCreateUserApi({
          custId: this.dataForm.id || 0,
          username: account,
          password: password,
          contactWay: this.dataForm.contactWay
        }).then(res => {
          this.$message.success('账号生成成功，账号和密码均为：' + account)
        }).catch(err => {
          this.$message.error('账号生成失败：' + (err.message || '未知错误'))
        })
      },
      // 表单数据提交
      dataSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.id) {
              api.cmcustUpdateApi(this.dataForm).then(function(res) {
                this.$message.success('保存成功')
                this.visible = false
                this.$emit('refreshDataList')
              }.bind(this));
            } else {
              api.cmcustCreateApi(this.dataForm).then(function(res) {
                this.$message.success('新增成功')
                this.visible = false
                this.$emit('refreshDataList')
              }.bind(this));
            }
          }
        })
      }
    }
  }
</script>
