<template>
  <div class="app-container">
    <!-- 筛选条件 -->
    <div class="screen-container">
      <Collapse :screen-form="screenForm">
        <template #right_btn>
          <el-button size="mini" @click="resetScreenForm">清空</el-button>
          <el-button size="mini" type="primary" @click="submitScreenForm">搜索</el-button>
        </template>

        <template #search>
          <el-form ref="screenForm" :model="screenForm" label-width="70px" size="mini" label-position="left">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="商户账号" prop="account">
                  <el-input v-model="screenForm.account" placeholder="请输入商户账号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="商户昵称" prop="nickname">
                  <el-input v-model="screenForm.nickname" placeholder="请输入商户昵称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="screenForm.phone" placeholder="请输入联系电话"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="电子邮箱" prop="email">
                  <el-input v-model="screenForm.email" placeholder="请输入电子邮箱"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="状态" prop="state">
                  <el-select v-model="screenForm.status" placeholder="全部">
                    <el-option label="全部" value=""></el-option>
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="(item, index) in select_status"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </Collapse>
    </div>

    <div class="mymain-container">
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button size="mini" type="primary" @click="toCreate()">开通账号</el-button>
        </div>
        <div class="fr">
          <ExportButton :exUrl="'admin/user/mch/export'" :exParams="exParams" />
        </div>
      </div>
      <div class="table">
        <el-table
          v-loading="listLoading"
          :data="dataList"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          stripe
        >
          <el-table-column align="center" label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="toDetail(scope.row.adminUserId)">详情</el-button>
              <template v-if="checkBtnRole('status')">
                <el-popconfirm
                  v-if="scope.row.status"
                  style="margin-left: 10px"
                  title="确定冻结吗？"
                  @onConfirm="changeStatus(scope.row.adminUserId, 0)"
                >
                  <el-button slot="reference" type="text">冻结</el-button>
                </el-popconfirm>
                <el-popconfirm
                  v-else
                  style="margin-left: 10px"
                  title="确定恢复吗？"
                  @onConfirm="changeStatus(scope.row.adminUserId, 1)"
                >
                  <el-button slot="reference" type="text">恢复</el-button>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
          <el-table-column align="center" label="商户账号" prop="userName" min-width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-button type="text" @click="toAccountList(scope.row)">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="商户昵称"
            prop="adminCompanyName"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="负责人"
            prop="linkName"
            min-width="100"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="角色"
            prop="roleName"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="联系电话"
            prop="linkPhone"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="金蝶主体账号"
            prop="useOrgNumber"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="金蝶主体名称"
            prop="useOrgName"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="电子邮箱"
            prop="email"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="地址"
            prop="address"
            min-width="200"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column align="center" label="状态" class-name="status-col">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status ? 'success' : 'danger'">{{ scope.row.status ? '正常' : '冻结' }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="pagination clearfix">
      <div class="fr">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="listTotal"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      title="详情"
      :visible.sync="detailDiaLog"
      width="600px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div>
        <el-form class="my-form" ref="mainForm" :model="mainForm" label-width="100px" label-position="right">
          <el-form-item label="商户账号" prop="account">
            <el-input v-model="mainForm.account" disabled class="formWidth"></el-input>
          </el-form-item>
          <el-form-item label="账户昵称" prop="nickName">
            <el-input v-model="mainForm.nickName" disabled class="formWidth"></el-input>
          </el-form-item>
          <el-form-item label="负责人" prop="chargePerson">
            <el-input v-model="mainForm.chargePerson" disabled class="formWidth"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="mainForm.phone" disabled class="formWidth"></el-input>
          </el-form-item>
          <el-form-item label="金蝶主体账号" prop="kingdeeId">
            <el-input v-model="mainForm.kingdeeId" disabled class="formWidth"></el-input>
          </el-form-item>
          <el-form-item label="金蝶主体名称" prop="kingdeeName">
            <el-input v-model="mainForm.kingdeeName" disabled class="formWidth"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="mainForm.email" disabled class="formWidth"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="mainForm.address" disabled class="formWidth"></el-input>
          </el-form-item>
          <el-form-item label="登录密码" prop="password">
            <el-input v-model="mainForm.password" type="password" disabled class="formWidth"></el-input>
            <el-button class="reset" @click="handleReset()">重置密码</el-button>
          </el-form-item>
          <!-- <el-form-item class="tr">
          <el-button type="primary" @click="submitmainForm">保存</el-button>
        </el-form-item> -->
        </el-form>

        <!-- 重置密码 -->
        <el-dialog
          append-to-body
          title="重置密码"
          :visible.sync="resetFormVisible"
          :show-close="false"
          width="500px"
          :close-on-click-modal="false"
        >
          <el-form ref="resetForm" :model="resetForm" :rules="resetFormRules" label-position="left" label-width="100px">
            <el-form-item label="输入新密码" prop="newPassword">
              <el-input
                v-model="resetForm.newPassword"
                ref="password1"
                autocomplete="off"
                class="formWidth"
                placeholder="请输入新密码"
                :type="passwordType1"
              ></el-input>
              <span class="show-pwd" @click="showPwd(1)">
                <svg-icon :icon-class="passwordType1 === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="resetForm.confirmPassword"
                ref="password2"
                autocomplete="off"
                class="formWidth"
                placeholder="请再次输入新密码"
                :type="passwordType2"
              ></el-input>
              <span class="show-pwd" @click="showPwd(2)">
                <svg-icon :icon-class="passwordType2 === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancelResetForm">取 消</el-button>
            <el-button type="primary" @click="submitResetForm">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDiaLog = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { COMMON_SELECT } from '@/utils/select_data'
import { getList, changeAccountStatus, getDetail, resetPassword, editAccount } from '@/api/merchant'
import { downloadFiles } from '@/utils/util'
import { getToken } from '@/utils/auth'

export default {
  // components:{MERCHANT_DETAIL},

  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入登录密码'))
      } else if (value.length < 12) {
        callback(new Error('密码长度至少12位'))
      } else if (/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/.test(value) == false) {
        callback(new Error('密码必须包含数字和字母'))
      } else {
        if (this.resetForm.confirmPassword !== '') {
          this.$refs.resetForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.resetForm.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: { 'x-token': getToken() },
      id: null,
      isCollapse: true,
      companyWechatId: null,
      step: 'first',
      mainForm: {
        account: '', // 账号
        nickName: '', // 用户名
        chargePerson: '', // 负责人
        phone: '', // 联系电话
        kingdeeId: '',
        kingdeeName: '',
        email: '', // 电子邮箱
        address: '', // 地址
        newPassword: '', // 新密码
        confirmPassword: '' // 确认密码
      },

      passwordType1: 'password',
      passwordType2: 'password',

      resetFormVisible: false,
      resetForm: {
        newPassword: '', // 新密码
        confirmPassword: '' // 确认密码
      },
      resetFormRules: {
        newPassword: [{ required: true, validator: validatePass, trigger: 'blur' }],
        confirmPassword: [{ required: true, validator: validatePass2, trigger: 'blur' }]
      },

      formLoading: false,

      detailDiaLog: false, //详情弹窗
      isOpen: false, // 是否展开条件筛选
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: null, // 列表数据
      listLoading: false, // 列表加载loading
      screenForm: {
        // 筛选表单数据
        account: '',
        nickname: '',
        phone: '',
        email: '',
        status: ''
      },
      select_status: [
        // 筛选字段 - 状态
        { label: '正常', value: true },
        { label: '冻结', value: false }
      ]
    }
  },
  created() {
    this.getList()
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened
      }
    },
    exParams() {
      return {
        userName: this.screenForm.account,
        nickName: this.screenForm.nickname,
        linkPhone: this.screenForm.phone,
        email: this.screenForm.email,
        status: this.screenForm.status
      }
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },

    // 重置密码
    handleReset(id) {
      this.resetId = id
      this.resetFormVisible = true
    },

    // 取消重置密码
    cancelResetForm() {
      this.resetFormVisible = false
      this.passwordType1 = 'password'
      this.passwordType2 = 'password'
      this.$refs.resetForm.resetFields()
    },

    // 提交重置密码
    submitResetForm() {
      this.$refs.resetForm.validate(valid => {
        if (valid) {
          let params = {
            password: this.resetForm.newPassword,
            adminUserId: this.id
          }
          resetPassword(params).then(res => {
            this.cancelResetForm()
            this.getDetail()
            this.$successMsg()
          })
        }
      })
    },

    // 显示隐藏密码
    showPwd(num) {
      if (num == 1) {
        if (this.passwordType1 === 'password') {
          this.passwordType1 = ''
        } else {
          this.passwordType1 = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password1.focus()
        })
      }
      if (num == 2) {
        if (this.passwordType2 === 'password') {
          this.passwordType2 = ''
        } else {
          this.passwordType2 = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password2.focus()
        })
      }
    },

    submitMainForm() {
      this.$refs.mainForm.validate(valid => {
        if (valid) {
          this.formLoading = true

          let params = {
            adminUserId: this.id,
            corpId: this.mainForm.enterpriseId,
            secret2: this.mainForm.listSecret,
            secret3: this.mainForm.listSyncSecret,
            agentId1: this.mainForm.appAgentId,
            secret1: this.mainForm.appSecret,
            appId: this.mainForm.appId,
            mchId: this.mainForm.merchantId,
            mchKey: this.mainForm.merchantKey,
            subAppId: this.mainForm.childAppId,
            subSecret: this.mainForm.childKey,
            subMchId: this.mainForm.childMerchantId,
            template: this.mainForm.templateId,
            companyWechatId: this.companyWechatId
          }
          editAccount(params)
            .then(res => {
              this.$successMsg('保存成功')
              setTimeout(() => {
                this.goBack()
              }, 1500)
            })
            .finally(res => {
              this.formLoading = false
            })
        }
      })
    },
    // 查询按钮权限
    checkBtnRole(value) {
      // let btnRole = this.$route.meta.roles;
      // if(!btnRole) {return true}
      // let index = btnRole.indexOf(value);
      // return index >= 0;
      return true
    },

    // 查询列表
    getList() {
      this.listLoading = true

      let params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        userName: this.screenForm.account,
        nickName: this.screenForm.nickname,
        linkPhone: this.screenForm.phone,
        email: this.screenForm.email,
        status: this.screenForm.status
      }

      getList(params).then(res => {
        this.dataList = res.data.records
        this.listTotal = res.data.total
        this.listLoading = false
      })
    },
    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1
      this.getList()
    },
    // 重置筛选表单
    resetScreenForm() {
        this.$refs.screenForm.resetFields()
      this.currentPage = 1
      this.getList()
    },
    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getList()
    },
    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 去开通账号
    toCreate() {
      this.$router.push({
        path: '/merchant/create_account',
        query: {}
      })
    },

    toAccountList() {
      this.$router.push({
        path: '/setting/account',
        query: {
          type: 1
        }
      })
    },

    async toDetail(id) {
      getDetail({ adminUserId: id }).then(res => {
        this.mainForm.account = res.data.userName
        this.mainForm.nickName = res.data.nickName
        this.mainForm.chargePerson = res.data.linkName
        this.mainForm.phone = res.data.linkPhone
        this.mainForm.kingdeeId = res.data.useOrgNumber
        this.mainForm.kingdeeName = res.data.useOrgName
        this.mainForm.email = res.data.email
        this.mainForm.address = res.data.address
        this.mainForm.password = '************'
        this.detailDiaLog = true
      })
    },

    // 操作 - 更改状态(type: 禁用0，启用1)
    changeStatus(id, type) {
      type = type ? true : false
      changeAccountStatus({ adminUserId: id, status: type }).then(res => {
        this.getList()
        this.$successMsg()
      })
    },

    // 导出
    handleExport() {
      let screenData = {
        userName: this.screenForm.account,
        nickName: this.screenForm.nickName,
        linkPhone: this.screenForm.phone,
        email: this.screenForm.email,
        status: this.screenForm.status
      }
      downloadFiles('admin/user/mch/export', screenData)
    }
  }
}
</script>

<style lang="scss" scoped>
.formWidth {
  width: 70%;
  margin-right: 20px;
}
</style>
