<!--
 * @Descripttion: 编辑账号
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-11-13 14:24:53
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-18 10:03:30
-->
<!--
<edit-account :edit-row="editRow"></edit-account>
import editAccount from '@/components/account/edit-account.vue';
-->
<template>
  <el-dialog :title="!!editRow.trialAccountId? '编辑账号':'新增账号'" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
    <div class="">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm" @submit.native.prevent>
        <el-form-item label="用户姓名" prop="trialAccountName">
          <el-input class="w-363"  v-model="ruleForm.trialAccountName" placeholder="请输入用户姓名" maxlength="40" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="用户手机号" prop="selfPhoneNumber">
          <el-input class="w-363"  v-model="ruleForm.selfPhoneNumber" placeholder="请输入用户手机号" maxlength="20" show-word-limit></el-input>
          <div v-if="!!editObj.selfPhoneNumber">
            <span class="color-f5222d">发现手机号重复，重复手机号</span><el-button type="text" @click="tryEnd(editObj)">立即结束</el-button> <el-button type="text" @click="toShowDetail">查看详情</el-button>
          </div>
        </el-form-item>
        <el-form-item label="试用账号" prop="trialAccount">
          <el-input class="w-363"  v-model="ruleForm.trialAccount" placeholder="请输入试用账号" maxlength="40" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="账号类型" prop="trialType">
          <el-radio v-model="ruleForm.trialType" label="1">手机号</el-radio>
          <el-radio v-model="ruleForm.trialType" label="2">企微账号</el-radio>
        </el-form-item>
        <el-form-item label="试用企业" prop="wxEnterpriseId">
          <el-popover placement="bottom" title="" width="363">
            <div class="select-search">
              <el-input placeholder="搜索企业/商户名称"  maxlength="50" v-model="searchSelect" style="width: 100%;" prefix-icon="el-icon-search" @keyup.native="value => toInput(value, searchSelect)" > </el-input>
            </div>
            <div class="daily-store-select">
              <div class="el-scrollbar define-search-select">
                <div class="el-select-dropdown__wrap el-scrollbar__wrap" style="overflow: auto;">
                  <ul class="el-scrollbar__view el-select-dropdown__list">
                    <li :class="['el-select-dropdown__item', item.wxEnterpriseId == ruleForm.wxEnterpriseId ? 'selected hover' : '']" v-for="item in companyData" :key="item.wxEnterpriseId" @click="checkCompany(item)">
                      <div class="flex flex-space-between">
                        <div>
                          <div class="text-ellipsis font-12 color-909399">{{ item.wxEnterpriseName || '--' }}</div>
                        </div>
                      </div>
                    </li>
                    <li v-if="!companyData.length" class="text-center"><span>暂无数据</span></li>
                  </ul>
                </div>
              </div>
            </div>
            <div class="show-select-num cursor-pointer " slot="reference">
              <div class="select-search-input">{{ ruleForm.wxEnterpriseName || '' }} <span v-if="!ruleForm.wxEnterpriseName" class="font-14 color-c0c4cc">请搜索试用企业</span></div>
            </div>
          </el-popover>
        </el-form-item>
        <el-form-item label="有效期" prop="">
          <el-date-picker class="w-363" v-model="ruleForm.effectDate" :picker-options="pickerOptions" type="date" placeholder="请选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item class="text-right">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" :loading="loadBtn" @click="submitForm('ruleForm')">立即创建</el-button>
        </el-form-item>
      </el-form>
      <account-detail v-if="showDetail" :edit-obj="editObj" @closeDetail="closeDetail"></account-detail>
    </div>
  </el-dialog>
</template>

<script>
import accountDetail from '@/components/account/account-detail.vue';
import { _debounce } from '@/common/js/public';
import fetch from '@/api/sql';
const { getEnterpriseList, saveAccount, getAccountDetail, setAccountStatus } = fetch;

import showMsg from '@/common/js/showmsg';
export default {
  name: 'EditAccount',
  components: { accountDetail },
  props: {
    editRow: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    let validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else {
        let reg = /^1[3456789]\d{9}$/;
        if (!reg.test(value)) {
          callback(new Error('手机号格式不正确'));
        } else {
          this.getPhoneDetail();
          callback();
        }
      }
    };
    return {
      userInfo: localStorage.getItem('haobanOperate') ? JSON.parse(localStorage.getItem('haobanOperate')) : { id: '', userMobile: '', realName: '', },
      dialogVisible: true,
      loadBtn: false,
      ruleForm: {
        trialAccountId: '',
        trialAccountName: '',
        selfPhoneNumber: '',
        wxEnterpriseName: '',
        trialType: '1',
        trialAccount: '',
        wxEnterpriseId: '',
        effectDate: ''
      },
      rules: {
        trialAccountName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
        ],
        selfPhoneNumber: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        trialAccount: [
          { required: true, message: '请输入试用账号', trigger: 'blur' }
        ],
        trialType: [
          { required: true, message: '请选择账号类型', trigger: 'change' }
        ],
        wxEnterpriseId: [
          { required: true, message: '请选择试用企业', trigger: 'change' }
        ],
      },
      pickerOptions: {
        disabledDate: time => {
          return time.getTime() < Date.now() - 24 * 3600 * 1000;
        }
      },
      searchSelect: '',
      companyData: [],
      editObj: {},
      showDetail: false
    };
  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    const that = this;
    that.getData();
    if (Object.keys(that.editRow).length) {
      that.ruleForm = JSON.parse(JSON.stringify(that.editRow));
    }
  },
  // methods
  methods: {
    /**
     * @description: 结束试用
     * @param {Object} row
     * @author: 无尘
     */
    tryEnd(row) {
      const that = this;
      that
        .$confirm('是否结束试用?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.postEnd(row);
        })
        .catch(() => {
        });
    },
    postEnd(row) {
      const that = this;
      const param = {
        trialAccountId: row.trialAccountId,
        commitId: that.userInfo.id,
        commitName: that.userInfo.realName
      };
      setAccountStatus(param).then(res => {
        if (res.code == '0000') {
          that.$message({
            message: '结束试用成功',
            type: 'success'
          });
          that.$emit('refreshData');
        }else{
          that.$message.error(res.message);
        }
      })
        .catch(function(error) {

        });
    },
    /**
     * @description: 显示详情
     * @author: 无尘
     */
    toShowDetail() {
      const that = this;
      that.showDetail = true;
    },
    closeDetail() {
      const that = this;
      that.showDetail = false;
    },
    /**
     * @description: 获取重复账号详情
     * @author: 无尘
     */
    getPhoneDetail() {
      const that = this;
      const para = {
        selfPhoneNumber: that.ruleForm.selfPhoneNumber,
      };
      getAccountDetail(para)
        .then(res => {
          if (res.code == '0000') {
            that.editObj = res.result || {};
          }
        })
        .catch(function(error) {
          that.editObj = {};
        });
    },
    /**
     * 输入
     */
    toInput: _debounce(function() {
      const that = this;
      that.getData();
    }, 300),
    getData() {
      const that = this;
      const para = {
        search: that.searchSelect,
        pageSize: 1000,
        pageNum: 1
      };
      getEnterpriseList(para)
        .then(res => {
          if (res.code == '0000') {
            that.companyData = res.result.result || [];
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 选择企业
     * @param {Object} item
     * @author: 无尘
     */
    checkCompany(item) {
      const that = this;
      that.ruleForm.wxEnterpriseName = item.wxEnterpriseName;
      that.ruleForm.wxEnterpriseId = item.wxEnterpriseId;
    },
    /**
     * @description: 关闭弹窗
     * @author: 无尘
     */
    handleClose() {
      const that = this;
      that.editObj = {};
      that.$emit('closeEdit');
      that.$refs['ruleForm'].resetFields();
    },
    cancelEdit() {
      const that = this;
      that.$emit('closeEdit');
      that.editObj = {};
      that.$refs['ruleForm'].resetFields();
    },
    /**
     * @description: 确定保存
     * @param {String} form
     * @returns {Boolean}
     * @author: 无尘
     */
    submitForm: _debounce(function(form) {
      const that = this;
      if (!!that.editObj.selfPhoneNumber) {
        return false;
      }
      that.loadBtn = true;
      that.$refs[form].validate(valid => {
        if (valid) {
          that.postAdd();
        } else {
          that.loadBtn = false;
          return false;
        }
      });
    }, 300),
    postAdd() {
      const that = this;
      let params = {
        trialAccountId: that.ruleForm.trialAccountId,
        trialAccountName: that.ruleForm.trialAccountName,
        selfPhoneNumber: that.ruleForm.selfPhoneNumber,
        wxEnterpriseName: that.ruleForm.wxEnterpriseName,
        trialType: that.ruleForm.trialType,
        trialAccount: that.ruleForm.trialAccount,
        wxEnterpriseId: that.ruleForm.wxEnterpriseId,
        effectDate: that.ruleForm.effectDate,
        commitId: that.userInfo.id,
        commitName: that.userInfo.realName
      };
      saveAccount(params)
        .then(res => {
          that.loadBtn = false;
          if (res.code == '0000') {
            showMsg.showmsg('保存成功', 'success');
            that.editObj = {};
            that.$emit('closeEdit', that.ruleForm);
            return false;
          }else {
            showMsg.showmsg(res.message, 'warning');
          }
        })
        .catch(function(error) {
          that.loadBtn = false;
        });
    },
  },
  watch: {
    editRow(newData) {
      const that = this;
      if (Object.keys(newData).length) {
        that.ruleForm = JSON.parse(JSON.stringify(newData));
      }
    }
  }
};
</script>
<style lang='less' scoped>
  .w-363 {
    width: 363px;
  }
  .selected {
    div {
      color: #2f54eb;
    }
  }
  .show-select-num {
    width: 363px;
    height: 32px;
    line-height: 32px;
    padding: 0 12px;
    font-size: 14px;
    color: #303133;
    border-radius: 2px;
    border: 1px solid #c4c6cf;
  }
</style>
