<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="注册时间" prop="createTime">
        <el-date-picker
          clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择注册时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="认证时间" prop="authTime">
        <el-date-picker
          clearable
          v-model="queryParams.authTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择认证时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="到期时间" prop="expireTime">
        <el-date-picker
          clearable
          v-model="queryParams.expireTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择到期时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="选择搜索条件">
        <el-select v-model="queryParams.searchField" placeholder="请选择搜索条件" clearable>
          <el-option
            v-for="dict in dict.type.buyer_company_search_fields"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键词搜索"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账号状态" prop="accountStatus">
        <el-select v-model="queryParams.accountStatus" placeholder="请选择账号状态" clearable>
          <el-option
            v-for="dict in dict.type.buyer_company_account_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="会员类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择会员类型" clearable>
          <el-option
            v-for="dict in dict.type.buyer_company_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['buyer:info:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['buyer:info:remove']"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['buyer:info:export']"
              >导出
              </el-button>
            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账号" align="center" prop="userName" />
      <el-table-column label="注册电话" align="center" prop="phone" />
      <el-table-column label="认证企业名称" align="center" prop="name" />
      <el-table-column label="会员类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.buyer_company_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="认证类型" align="center" prop="authStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.buyer_company_auth_status" :value="scope.row.authStatus" />
        </template>
      </el-table-column>
      <el-table-column label="账号状态" align="center" prop="accountStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.buyer_company_account_status" :value="scope.row.accountStatus" />
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="认证时间" align="center" prop="authTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.authTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到期时间" align="center" prop="expireTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleBlockUp(scope.row)"
            v-hasPermi="['buyer:info:edit']"
          >
            {{ scope.row.accountStatus === '1' ? '启用' : '停用' }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['buyer:info:edit']"
          >手动充值
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['buyer:info:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会员企业信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="950px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 充值信息-->
        <div class="detail-info" v-if="isUpdate">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-descriptions title="账号信息" :column="1" :labelStyle="{color:'#aaa'}">
                <el-descriptions-item label="账号">{{ form.userName }}</el-descriptions-item>
                <el-descriptions-item label="注册电话">{{ form.phone }}</el-descriptions-item>
                <el-descriptions-item label="账号状态">
                  <dict-tag :options="dict.type.buyer_company_account_status" :value="form.accountStatus" />
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions title="认证信息" :column="1" :labelStyle="{color:'#aaa'}">
                <el-descriptions-item label="企业名称">{{ form.name }}</el-descriptions-item>
                <el-descriptions-item label="信用代码">{{ form.code }}</el-descriptions-item>
                <el-descriptions-item label="认证状态">
                  <dict-tag :options="dict.type.buyer_company_auth_status" :value="form.authStatus" />
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-descriptions title="会员信息" :column="1" :labelStyle="{color:'#aaa'}">
                <el-descriptions-item label="会员类型">
                  <dict-tag :options="dict.type.buyer_company_type" :value="form.type" />
                </el-descriptions-item>
                <el-descriptions-item label="会员到期时间">{{ form.isExpire == '1' ? '已到期' : form.expireTime }}</el-descriptions-item>
                <el-descriptions-item label="会员剩余时长">{{ form.endLength }}</el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
          <el-form-item label="充值时长" prop="duration" :rules="[{ required: true, message: '请填写充值时长', trigger: ['change', 'blur'] }]">
            <el-input v-model="form.duration" type="number" placeholder="请输入充值时长" style="width: 150px" />
            <el-select v-model="form.unit" placeholder="请选择单位" :style="{width: '80px',marginLeft:'15px'}">
              <el-option
                v-for="dict in dict.type.buyer_duration_unit"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <!-- 新增表单-->
        <div class="company-add-form" v-else>
          <div class="account-info">
            <div class="title">账号信息</div>
            <el-form-item label="账号" prop="userName">
              <el-input v-model="form.userName" type="text" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入电话号码" />
            </el-form-item>
            <!--            <el-form-item label="验证码" prop="verifyCode">
                          <el-input
                            v-model="form.verifyCode"
                            auto-complete="off"
                            placeholder="请输入验证码"
                            style="width: 63%"
                          >
                          </el-input>
                          <el-button class="code-form-item" type="primary" v-if="!isSendCode" @click="sendCode">获取验证码</el-button>
                          <span v-else class="code-form-item">{{ waitSecond }}s后可重新获取</span>
                        </el-form-item>-->
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="form.password"
                type="password"
                auto-complete="off"
                placeholder="请输入密码"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="再次输入" prop="confirmPassword">
              <el-input
                v-model="form.confirmPassword"
                type="password"
                auto-complete="off"
                placeholder="请再次输入密码"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="状态" prop="accountStatus">
              <el-radio-group v-model="form.accountStatus">
                <el-radio
                  v-for="dict in dict.type.buyer_company_account_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="auth-info">
            <div class="title">认证信息</div>
            <el-form-item label="营业执照" prop="fileNames">
              <ImageUpload v-model:value="form.fileNames" :limit="1" :file-size="1" :drag="true"></ImageUpload>
            </el-form-item>
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入企业名称" />
            </el-form-item>
            <el-form-item label="信用代码" prop="code">
              <el-input v-model="form.code" placeholder="请输入统一信用代码" />
            </el-form-item>
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="form.contacts" placeholder="请输入联系人" />
            </el-form-item>
            <el-form-item label="联系电话" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入企业联系人电话" />
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo, rechargeCompany } from '@/api/buyer/company'
import { deepClone } from '@/utils'

export default {
  name: 'Info',
  dicts: [
    'buyer_company_account_status',
    'buyer_company_auth_status',
    'buyer_company_type',
    'buyer_company_search_fields',
    'buyer_duration_unit'
  ],
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.form.password !== value) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员企业信息表格数据
      infoList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        accountStatus: null,
        authTime: null,
        expireTime: null,
        registerTime: null,
        // 搜索字段
        searchField: null,
        // 关键词
        keyword: null,
        type: null
      },
      // 表单参数
      form: {
        userName: null,
        phone: null,
        verifyCode: null,
        password: null,
        confirmPassword: null,
        accountStatus: null,
        businessLicense: null,
        name: null,
        code: null,
        contacts: null,
        phoneNumber: null,
        unit: 'hour'
      },
      isUpdate: false,
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: 'blur', message: '请输入您的密码' },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, trigger: 'blur', message: '请再次输入您的密码' },
          { required: true, validator: equalToPassword, trigger: 'blur' }
        ],
        accountStatus: [
          { required: true, message: '请选择账号状态', trigger: 'change' }
        ],
        fileNames: [
          { required: true, message: '请上传营业执照', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入统一信用代码', trigger: 'blur' }
        ],
        contacts: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      isSendCode: false,
      waitSecond: 60
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 发送验证码
    sendCode() {
      this.isSendCode = true
      if (this.isSendCode) {
        let timer = setInterval(() => {
          if (this.waitSecond > 0) {
            this.waitSecond--
          } else {
            clearInterval(timer)
            this.isSendCode = false
          }
        }, 1000)
      }
    },
    /** 查询会员企业信息列表 */
    getList() {
      this.loading = true
      listInfo(this.addSearchField(this.queryParams, this.queryParams.searchField, this.queryParams.keyword)).then(response => {
        this.infoList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        userName: null,
        phone: null,
        verifyCode: null,
        password: null,
        confirmPassword: null,
        accountStatus: null,
        businessLicense: null,
        name: null,
        code: null,
        contacts: null,
        phoneNumber: null,
        unit: 'hour'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
          pageSize: 10,
          accountStatus: null,
          authTime: null,
          expireTime: null,
          registerTime: null,
          // 搜索字段
          searchField: null,
          // 关键词
          keyword: null,
          type: null
      }
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.isUpdate = false
      this.open = true
      this.title = '添加会员企业信息'
    },
    /** 停用账号 */
    handleBlockUp(row) {
      let params = deepClone(row)
      let text = ''
      if (params.accountStatus === '0') {
        text = '停用'
        params.accountStatus = '1'
      } else {
        text = '启用'
        params.accountStatus = '0'
      }
      this.$modal.confirm(`确认${text}该会员吗？${params.accountStatus === '1' ? '停用后该会员下所有账号均不能登录！' : ''}`)
        .then(function() {
          return updateInfo(params)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(`${text}成功`)
        })
        .catch(() => { })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.isUpdate = true
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data
        this.form.unit = 'hour'
        this.open = true
        this.title = '修改会员企业信息'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            rechargeCompany(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除会员企业信息账号为"' + row.userName + '"的数据项？').then(function() {
        return delInfo(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('buyer/company/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped lang="scss">
.company-add-form {
  display: flex;

  .account-info {
    flex: 1;
  }

  .auth-info {
    flex: 1;
    margin-left: 15px;
  }

  .title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
  }

  .code-form-item {
    display: inline-block;
    margin-left: 15px;
  }
}
</style>
