<!--  -->
<template>
  <div>
    <div class="pending">
      <!-- 搜索 -->
      <div class="formSearch">
        <el-form :inline="true" :model="formInline">
          <el-form-item label="店铺名称">
            <el-input v-model="formInline.shopName" maxlength="20" placeholder="请输入店铺名称" />
          </el-form-item>
          <el-form-item label="店铺编码">
            <el-input v-model="formInline.shopCode" maxlength="20" placeholder="请输入店铺编码" />
          </el-form-item>
          <el-form-item label="负责人">
            <el-input v-model="formInline.chargePersonName" maxlength="20" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item label="合同状态">
            <el-select v-model="formInline.contractState" placeholder="请选择">
              <el-option label="有效" value="1" />
              <el-option label="无效" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="onSubmit">
              查询
            </el-button>
            <el-button type="success" plain @click="addbuss">
              新建商家
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <div class="tableBox">
        <el-table
          ref="multipleTable" :data="tableData" border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }" tooltip-effect="dark" style="width: 100%"
        >
          <el-table-column label="店铺名称" width="220">
            <template slot-scope="scope">{{ scope.row.shopName }}</template>
          </el-table-column>
          <el-table-column prop="shopCode" label="店铺编码" />
          <el-table-column prop="chargePersonName" label="负责人" />
          <el-table-column prop="chargePersonPhone" label="联系电话" />
          <el-table-column label="合同状态">
            <template slot-scope="scope">
              <span v-if="scope.row.contractState === 0">无效</span>
              <span v-if="scope.row.contractState === 1">有效</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column label="操作" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="btnList">
                <el-button type="text" @click="seeMore(scope.row)">
                  查看
                </el-button>
                <el-button type="text" @click="edit(scope.row)">
                  编辑
                </el-button>
                <el-button v-if="scope.row.state == 1" type="text" @click="del(scope.row)">
                  禁用
                </el-button>
                <el-button v-else type="text" @click="del(scope.row)">
                  启用
                </el-button>
                <el-button type="text" @click="delBusiness(scope.row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="fenye">
          <el-pagination
            :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="10"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <!-- ******************************************************弹框开始****************************************************** -->
      <!-- 新建商家弹框 -->
      <el-dialog
        :title="userState === 0
          ? '新增商家'
          : userState === 1
            ? '修改商家'
            : '查看商家'
        " :visible.sync="dialogVisible" width="30%" center
        :close-on-click-modal="false"
      >
        <div>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="授权信息" name="first">
              <el-form ref="ruleFormInfo" :model="ruleForm" :rules="rulesInfo" label-width="120px">
                <el-form-item label="店铺名称" prop="shopName">
                  <el-input v-model="ruleForm.shopName" maxlength="20" :disabled="disabled" />
                </el-form-item>
                <el-form-item label="店铺负责人" prop="chargePersonName">
                  <el-input v-model="ruleForm.chargePersonName" maxlength="20" :disabled="disabled" />
                </el-form-item>
                <el-form-item label="负责人电话" prop="chargePersonPhone">
                  <el-input
                    v-if="cpPhoneShow" :value="hidden(ruleForm.chargePersonPhone, 3, 4)" maxlength="11"
                    :disabled="disabled" @focus="focuscpPhoneInput"
                  />
                  <el-input
                    v-else ref="cpPhoneCls" v-model="ruleForm.chargePersonPhone" maxlength="11"
                    clearable
                    :disabled="disabled" @change="changecpPhoneInput"
                  />
                </el-form-item>
                <el-form-item label="店铺地址" prop="shopAdress">
                  <el-input ref="addressCls" v-model="ruleForm.shopAdress" maxlength="60" :disabled="disabled" />
                  <!-- <div v-else @click="inputAddress">
                    <el-input :value="hidden(ruleForm.shopAdress, 1, 1)" :disabled="disabled" />
                  </div> -->
                </el-form-item>
                <el-form-item label="生效日期" prop="effectiveDate">
                  <el-date-picker
                    v-model="ruleForm.effectiveDate" :disabled="disabled" value-format="yyyy-MM-dd"
                    type="date" placeholder="选择日期"
                  />
                </el-form-item>
                <el-form-item label="生效年限" prop="effectiveYear">
                  <el-input
                    v-model="ruleForm.effectiveYear" type="text" :disabled="disabled" placeholder="请输入内容"
                    maxlength="4" class="elipt" style="width: 50%" show-word-limit
                  />
                  <span class="elspan">年</span>
                </el-form-item>
                <el-form-item label="合同状态" prop="contractState">
                  <el-radio-group v-model="ruleForm.contractState">
                    <el-radio :disabled="disabled" :label="1">
                      有效
                    </el-radio>
                    <el-radio :disabled="disabled" :label="0">
                      无效
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="直播间审核" prop="auditLive">
                  <el-radio-group v-model="ruleForm.auditLive">
                    <el-radio :disabled="disabled" :label="1">
                      开启
                    </el-radio>
                    <el-radio :disabled="disabled" :label="0">
                      关闭
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="直播间商品审核" prop="auditLiveProduct">
                  <el-radio-group v-model="ruleForm.auditLiveProduct">
                    <el-radio :disabled="disabled" :label="1">
                      开启
                    </el-radio>
                    <el-radio :disabled="disabled" :label="0">
                      关闭
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="客户信息" name="second">
              <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
                <el-form-item label="账号" prop="shopPhone">
                  <el-input
                    v-if="shopPhoneShow" :value="hidden(ruleForm.shopPhone, 3, 4)" :disabled="disabled"
                    maxlength="20" @focus="focusShopPhoneInput"
                  />
                  <el-input v-else ref="shopPhoneCls" v-model="ruleForm.shopPhone" :disabled="disabled" maxlength="20" />
                </el-form-item>
                <el-form-item label="密码" prop="shopPassword">
                  <el-input v-model="ruleForm.shopPassword" type="password" :disabled="disabled" maxlength="16" />
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeFn">取 消</el-button>
          <el-button v-if="activeName == 'first'" type="primary" @click="next">下一步</el-button>
          <el-button v-else type="primary" @click="addCheck('ruleForm')">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import {
  businessListGetAll,
  businessListSave,
  businessListGetById,
  businessListUpdate,
  businessListStart,
  delBusinessById
} from '@/api/business'

export default {
  components: {},
  data() {
    // 这里存放数据
    return {
      // 新建商家弹框
      dialogVisible: false,
      activeName: 'first',
      formInline: {
        shopName: '', // 店铺名称
        shopCode: '', // 店铺编码
        chargePersonName: '', // 店铺负责人
        contractState: '', // 合同状态 1-有效 0-无效
        page: '1', // 当前页
        pageSize: '10' // 每页记录数
      },
      disabled: false,
      ruleForm: {
        shopName: '', // 店铺名称
        chargePersonName: '', // 店铺负责人
        chargePersonPhone: '', // 负责人电话
        shopAdress: '', // 地址
        effectiveDate: '', // 生效日期
        effectiveYear: '', // 生效年限
        contractState: 1, // 合同状态 1-有效 0-无效
        auditLive: 1,
        auditLiveProduct: 1,
        shopPhone: '', // 账号
        shopPassword: '' // 密码
      },
      showPhone: false,
      showAddress: false,
      userPhone: '',
      showUserPhone: false,
      newAddress: '',
      personPhone: '',

      rulesInfo: {
        effectiveYear: [
          { required: true, message: '请输入生效时限', trigger: 'blur' }
        ],
        shopName: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' }
        ],
        chargePersonName: [
          { required: true, message: '请输入店铺负责人', trigger: 'blur' }
        ],
        chargePersonPhone: [
          { required: true, message: '请输入负责人电话', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '目前只支持中国大陆的手机号码'
          }
        ],
        shopAdress: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        contractState: [
          {
            required: true,
            message: '请选择合同状态',
            trigger: 'change'
          }
        ],
        auditLive: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'change'
          }
        ],
        auditLiveProduct: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'change'
          }
        ],
        effectiveDate: [
          {
            required: true,
            message: '请选择日期',
            trigger: 'change'
          }
        ]
      },
      rules: {
        shopPhone: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '目前只支持中国大陆的手机号码'
          }
        ],
        shopPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },

          {
            pattern: /^[~!@#$%^&*\-+=_.0-9a-zA-Z]{8,16}$/,
            message: '8-16密码数字英文混合'
          }
        ]
      },
      total: 1,
      tableData: [],
      currentPage: 1,
      userState: 1,
      privacyTime: 0,
      cpPhoneShow: true, // 是否显示脱敏负责人手机号
      shopPhoneShow: true // 是否显示脱敏账号
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getAll(this.formInline)
    this.privacyTime = localStorage.getItem('privacyTime')
    console.log(this.privacyTime)
  },
  // 方法集合
  methods: {
    focusShopPhoneInput() {
      this.shopPhoneShow = false
      this.ruleForm.shopPhone = ''
      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs.shopPhoneCls.focus()
      })
    },
    focuscpPhoneInput() {
      this.cpPhoneShow = false
      this.ruleForm.chargePersonPhone = ''
      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs.cpPhoneCls.focus()
      })
    },
    changecpPhoneInput() {
    },
    handleSizeChange(val) {
      this.formInline.pageSize = val
      this.getAll(this.formInline)
    },
    handleCurrentChange(val) {
      this.formInline.page = val
      this.getAll(this.formInline)
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    onSubmit() {
      this.getAll(this.formInline)
    },
    // 新建商家
    addbuss() {
      this.userState = 0
      this.disabled = false
      this.newAddress = ''
      this.personPhone = ''
      this.ruleForm = {
        shopName: '', // 店铺名称
        chargePersonName: '', // 店铺负责人
        chargePersonPhone: '', // 负责人电话
        shopAdress: '', // 地址
        effectiveDate: '', // 生效日期
        effectiveYear: '', // 生效年限
        contractState: 1, // 合同状态 1-有效 0-无效
        auditLive: 1,
        auditLiveProduct: 1,
        shopPhone: '', // 账号
        shopPassword: '' // 密码
      }
      this.dialogVisible = true
      console.log(this.userState)
    },
    next() {
      this.activeName = 'second'
    },
    closeFn() {
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate()
        this.$refs.ruleFormInfo.clearValidate()
        this.dialogVisible = false
      })
    },
    // 新建商家确定
    addCheck(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          console.log(this.userState)
          console.log(this.ruleForm)
          if (this.personPhone !== '') {
            this.ruleForm.chargePersonPhone = this.personPhone
          }
          if (this.newAddress !== '') {
            this.ruleForm.shopAdress = this.newAddress
          }
          if (this.userPhone !== '') {
            this.ruleForm.shopPhone = this.userPhone
          }
          if (this.ruleForm.shopName === '') {
            this.$message.error('请输入店铺名称')
            return
          }
          if (this.ruleForm.effectiveDate === '') {
            this.$message.error('请输入生效日期')
            return
          }
          if (this.ruleForm.effectiveYear === '') {
            this.$message.error('请输入生效年限')
            return
          }
          if (!this.userState) {
            businessListSave(this.ruleForm).then((res) => {
              console.log(res)
              if (res.code === '') {
                this.$message({
                  message: '新增成功',
                  type: 'success'
                })
              }
              this.getAll(this.formInline)
              this.dialogVisible = false
              this.$refs.ruleForm.clearValidate()
            })
          } else {
            businessListUpdate(this.ruleForm).then((res) => {
              console.log(res)
              if (res.code === '') {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.$refs.ruleForm.clearValidate()
              }
              this.getAll(this.formInline)
              this.dialogVisible = false
            })
          }
        } else {
          console.log('error submit!!')
          this.$message.error('请输入完整信息')
          return false
        }
      })
    },
    // 查看
    async seeMore(row) {
      this.showPhone = false
      this.cpPhoneShow = true
      this.shopPhoneShow = true
      const res = await businessListGetById({ shopId: row.shopId })
      if (res.code === '') {
        this.userState = 3
        this.disabled = true
        this.ruleForm = res.data
        this.dialogVisible = true
      }
    },
    // 编辑
    async edit(row) {
      this.showPhone = false
      this.personPhone = ''
      this.userState = 1
      this.disabled = false
      this.cpPhoneShow = true
      const res = await businessListGetById({ shopId: row.shopId })
      this.ruleForm = res.data
      this.dialogVisible = true
      console.log(this.ruleForm)
    },
    // 删除
    async del(row) {
      console.log(row)
      if (row.state === 1) {
        const res = await businessListStart({
          shopName: row.shopName,
          state: 0,
          shopId: row.shopId
        })
        if (res.code === '') {
          this.$message({
            message: '停用成功',
            type: 'success'
          })
          this.getAll(this.formInline)
        }
      } else {
        const res = await businessListStart({
          shopName: row.shopName,
          state: 1,
          shopId: row.shopId
        })
        if (res.code === '') {
          this.$message({
            message: '启用成功',
            type: 'success'
          })
          this.getAll(this.formInline)
        }
      }
    },
    delBusiness(row) {
      // todo 判断商家状态
      this.$confirm('此操作将永久删除该商家, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await delBusinessById({
          shopId: row.shopId
        })
        if (res.code === '') {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getAll(this.formInline)
        }
      })
        .catch(() => {

        })
    },
    // businessListGetAll
    // 初始化查询所有数据
    async getAll(formInline) {
      const res = await businessListGetAll(formInline)
      this.total = res.data.total
      this.tableData = res.data.list
    },
    // 编辑号码
    inputPhone() {
      this.showPhone = true
      this.personPhone = ''
      this.$nextTick(() => {
        this.$refs.phoneCls.focus()
      })
    },
    // 编辑地址
    inputAddress() {
      this.showAddress = true
      this.newAddress = ''
      this.$nextTick(() => {
        this.$refs.addressCls.focus()
      })
    },
    // 编辑客户信息
    inputUserPhone() {
      this.showUserPhone = true
      this.userPhone = ''
      this.$nextTick(() => {
        this.$refs.userPhoneCls.focus()
      })
    },
    // 中间部分
    hidden(str, frontLen, endLen) {
      let endLenData = 0
      if (str.length !== 2) {
        endLenData = endLen
      }
      const len = str.length - frontLen - endLenData
      let xing = ''
      for (let i = 0; i < len; i++) {
        xing += '*'
      }
      return (
        str.substring(0, frontLen) + xing + str.substring(str.length - endLenData)
      )
    }
  }
}
</script>

<style
  lang="scss"
  scoped
>
@import url("../../../styles/elDialog.scss");

.pending {
	padding: 30px;
}

.fenye {
	margin-top: 20px;
}

.elipt {
	width: 50%;
}

.elspan {
	margin-left: 10px;
}
</style>
