<template>
  <div class="app-container personal-info">
    <div class="title">公司信息</div>
    <el-divider />
    <el-row>
      <el-col :span="5">公司名称：</el-col>
      <el-col :span="19">{{ supplierInfo.shopName }}</el-col>
    </el-row>
    <el-divider />
    <el-row>
      <el-col :span="5">所属类型：</el-col>
      <el-col :span="8">{{ supplierInfo.shopType === 1 ? '品牌方' : '代理商' }}</el-col>
    </el-row>
    <el-divider />
    <el-row>
      <el-col :span="5">手机号：</el-col>
      <el-col :span="8">{{ supplierInfo.mobile }}</el-col>
      <el-col :span="8">
        <router-link class="link" to="/personal/mobile"><i class="el-icon-edit" /><span>修改手机号</span></router-link>
      </el-col>
    </el-row>
    <el-divider />
    <el-row>
      <el-col :span="5">联系人：</el-col>
      <el-col :span="8">{{ supplierInfo.linkMan }}</el-col>
      <el-col :span="8">
        <el-link icon="el-icon-edit" type="primary" @click="onEditContactName">修改联系人</el-link>
      </el-col>
    </el-row>
    <el-divider />
    <el-row>
      <el-col :span="5">公司logo：</el-col>
      <el-col :span="8">
        <preview-image :src="supplierInfo.logo" />
        <div style="margin-top: 12px">
          <el-link icon="el-icon-upload" type="primary" @click="onEditLogo">修改</el-link>
        </div>
      </el-col>
    </el-row>
    <el-divider />
    <el-row>
      <el-col :span="5">登录账号：</el-col>
      <el-col :span="8">{{ supplierInfo.loginAccount ? supplierInfo.loginAccount : '暂未绑定' }}</el-col>
      <el-col v-if="!supplierInfo.loginAccount" :span="8">
        <router-link class="link" to="/personal/account"><i class="el-icon-link" /><span>去绑定</span></router-link>
      </el-col>
    </el-row>
    <el-divider />
    <el-row>
      <el-col :span="5">旗下品牌：</el-col>
      <el-col :span="19">
        <div class="tag-list">
          <template v-for="(item, index) in brandList">
            <el-tag
              :key="index"
              closable
              effect="dark"
              size="small"
              type="success"
              @close="onRemoveBrand(item, index)"
              @click="onEditBrand('edit', item, index)"
            >
              <span>{{ item.brandName }}</span>
            </el-tag>
          </template>
          <el-tag
            effect="dark"
            type="primary"
            size="small"
            @click="onEditBrand('add')"
          >添加品牌<span
            class="el-icon-plus"
          /></el-tag>
        </div>
      </el-col>
    </el-row>
    <el-divider />
    <el-row>
      <el-col :span="5">会员状态：</el-col>
      <el-col :span="8">
        <span v-if="supplierInfo.vipStatus === 1">会员</span>
        <span v-if="supplierInfo.vipStatus === 3">非会员</span>
      </el-col>
      <el-col :span="8">
        <router-link v-if="supplierInfo.vipStatus === 3" class="link" to="/vip/vip-open">
          <i class="el-icon-thumb" /><span>开通会员</span>
        </router-link>
        <router-link v-if="supplierInfo.vipStatus === 1" class="link" to="/vip/vip-open">
          <i class="el-icon-thumb" /><span>续费会员</span>
        </router-link>
      </el-col>
    </el-row>

    <!-- 品牌编辑dialog -->
    <el-dialog
      :title="eidtText"
      width="36%"
      :visible.sync="editVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <template v-if="editType < 2">
        <brand-edit-form v-if="editVisible" ref="brandEditForm" :model="brandModel" @change="onBrandFormChange" />
      </template>
      <template v-else>
        <el-form v-if="editVisible" ref="submitForm" label-width="80px" :model="formData" :rules="rules">
          <el-form-item v-if="editType === 2" label="logo：" prop="logo">
            <el-input v-show="false" v-model="formData.logo" />
            <upload-image
              tip="建议尺寸：200px * 200px"
              :image-list="logoImageList"
              @success="onUploadLogoSuccess"
              @remove="onRemoveLogoImage"
            />
          </el-form-item>
          <el-form-item v-if="editType === 3" label="联系人：" prop="linkMan">
            <el-input v-model="formData.linkMan" placeholder="请输入联系人" />
          </el-form-item>
        </el-form>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSupplierById,
  updateSupplierLinkMan,
  updateSupplierLogo,
  saveSupplierShopInfo,
  deleteSupplierShopInfo
} from '@/api/supplier'
import UploadImage from '@/components/UploadImage'
import { BrandEditForm } from '@/views/components'
import { deepClone } from '@/utils'

const generateBrandInfo = () => ({
  infoId: '',
  brandName: '',
  brandLogo: '',
  producePlace: '',
  manufacturer: ''
})

export default {
  components: {
    UploadImage,
    BrandEditForm
  },
  data() {
    return {
      editType: 0,
      editVisible: false,
      brandEditType: 'add',
      brandEditIndex: 0,
      supplierInfo: {},
      brandList: [],
      brandModel: generateBrandInfo(),
      formData: {
        logo: '',
        linkMan: ''
      },
      rules: {
        logo: [{ required: true, message: '请上传logo', trigger: 'change' }],
        linkMan: [{ required: true, message: '请输入联系人', trigger: 'blur' }]
      },
      logoImageList: []
    }
  },
  computed: {
    eidtText() {
      const eidtText = ['添加品牌', '修改品牌', '修改logo', '修改联系人']
      return eidtText[this.editType]
    }
  },
  created() {
    this.fetchSupplierInfo()
  },
  methods: {
    // 获取供应商信息
    fetchSupplierInfo() {
      getSupplierById({ authUserId: this.$store.getters.authUserId }).then((res) => {
        console.log(res)
        this.supplierInfo = res.data
        this.brandList = res.data.shopInfo
      })
    },
    // 品牌信息变化
    onBrandFormChange(data) {
      this.brandModel = data
    },
    // 编辑品牌事件
    onEditBrand(type, row, index) {
      this.editType = type === 'add' ? 0 : 1
      this.brandEditType = type
      this.brandEditIndex = index
      this.brandModel = type === 'add' ? generateBrandInfo() : row
      this.editVisible = true
    },
    // 删除品牌操作
    async onRemoveBrand(item, index) {
      // 判断品牌是否可删除
      let existInfoIds = this.formData.existProductInfoIds
      existInfoIds = existInfoIds ? existInfoIds.split(',') : []
      const exist = existInfoIds.indexOf(item.infoId.toString()) > -1
      if (exist) {
        this.$alert('对不起，该品牌已绑定设备认证，暂时无法删除！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {})
        return
      }
      try {
        await this.$confirm('确认删除该品牌信息？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await this.removeBrand(item, index)
      } catch (error) {
        console.log(error)
        this.$message.info('已取消操作')
      }
    },
    async removeBrand(item, index) {
      try {
        await deleteSupplierShopInfo({ infoId: item.infoId })
        this.$message.success('成功删除品牌')
        this.brandList.splice(index, 1)
      } catch (error) {
        console.log(error)
      }
    },
    // 品牌信息确认提交
    async onBrandSubmit() {
      try {
        await this.$refs.brandEditForm.validate()
        await this.onBrandSave()
      } catch (error) {
        console.log(error)
      }
    },

    async onBrandSave() {
      try {
        await saveSupplierShopInfo(deepClone(this.brandModel))
        this.$message.success('品牌信息已保存')
        this.editVisible = false
      } catch (error) {
        console.log(error)
      }
    },

    // 编辑取消
    onCancel() {
      this.editVisible = false
    },
    // 编辑提交
    async onSubmit() {
      const action = {
        0: this.onBrandSubmit,
        1: this.onBrandSubmit,
        2: this.onLogoSubmit,
        3: this.onContactSubmit
      }
      try {
        await this.$refs.submitForm?.validate()
        await action[this.editType]()
      } catch (error) {
        console.log(error)
      } finally {
        this.fetchSupplierInfo()
        // this.editVisible = false
      }
    },
    // logo编辑
    onEditLogo() {
      this.editType = 2
      this.editVisible = true
    },
    // logo编辑提交
    async onLogoSubmit() {
      try {
        await updateSupplierLogo({ logo: this.formData.logo })
        this.$message.success('修改logo成功')
        this.editVisible = false
      } catch (error) {
        console.log(error)
      } finally {
        this.logoImageList = []
      }
    },
    // 编辑联系人
    onEditContactName() {
      this.editType = 3
      this.editVisible = true
    },
    // 联系人编辑提交
    async onContactSubmit() {
      try {
        await updateSupplierLinkMan({ linkMan: this.formData.linkMan })
        this.$message.success('修改联系人成功')
        this.editVisible = false
      } catch (error) {
        console.log(error)
      }
    },
    // 供应商logo上传成功
    onUploadLogoSuccess({ response, file, fileList }) {
      this.logoImageList = fileList
      this.formData.logo = response.data
    },
    // 移除供应商logo
    onRemoveLogoImage() {
      this.logoImageList = []
      this.formData.logo = ''
    }
  }
}
</script>

<style scoped lang="scss">
.personal-info {
  width: 600px;
  margin: 0 auto;
  margin-top: 60px;
  color: #101010;
  .link {
    color: #409eff;
    font-size: 14px;
    &:hover {
      text-decoration: underline;
    }
  }

  .el-row {
    .el-col:nth-child(2) {
      color: #404040;
    }
  }
}
.title {
  font-size: 24px;
  font-weight: bold;
}
.tag-list {
  margin-top: -10px;
  .el-tag {
    cursor: pointer;
    margin-right: 8px;
    margin-top: 8px;
  }
}

.el-divider {
  margin: 16px 0;
}
</style>
