<template>
	<zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title+'-列表', essential: true }]">
		<template slot-scope="{activeKey, data}">
			<div v-if="activeKey == 'list'" class="app-container">
			  <div class="btn-group clearfix">
			    <div class="fl">
			      <el-button v-if="$restrict('add')" size="small" type="primary" icon="el-icon-plus" @click="addOrEdit('add')">添加品牌</el-button>
			    </div>
			  </div>

			  <div class="table">
			    <el-table ref="noticeTable" v-loading="listLoading" :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe>
			      <el-table-column align="center" label="服务品牌" prop="brandName" min-width="180"></el-table-column>
			      <el-table-column align="center" label="图片" prop="imageUrl">
			        <template slot-scope="scope">
			          <el-image style="width: 40px; height: 40px; display: block; margin: 0 auto;" :src="$showImgUrl(scope.row.imageUrl)" :preview-src-list="[$showImgUrl(scope.row.imageUrl)]" fit="cover">
			            <div slot="error" style="height: 100%;font-size: 40px;">
			              <i class="el-icon-picture-outline"></i>
			            </div>
			          </el-image>
			        </template>
			      </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-column align="center" label="排序" prop="sortNum"></el-table-column>
			      <el-table-column align="center" label="创建人" prop="createBy" min-width="100"></el-table-column>
			      <el-table-column align="center" label="创建时间" prop="createTime" min-width="160"></el-table-column>
			      <el-table-column align="center" label="修改人" prop="updateBy" min-width="100"></el-table-column>
			      <el-table-column align="center" label="修改时间" prop="updateTime" min-width="160"></el-table-column>
			      <el-table-column align="center" label="操作" fixed="right" width="120">
			        <template slot-scope="scope">
			          <el-button type="text" v-if="$restrict('edit')" @click="addOrEdit('edit', scope.row.id)">编辑</el-button>
			          <el-popconfirm v-if="$restrict('del')" style="margin-left: 10px;" title="确定删除吗？" @confirm="handleDelete(scope.row.id)">
			            <el-button slot="reference" type="text">删除</el-button>
			          </el-popconfirm>
			        </template>
			      </el-table-column>
			    </el-table>
			  </div>
			</div>
			<!-- 新增编辑 -->
			<div v-if="addFormVisible" class="app-container">
				<el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="left" label-width="80px">
					<el-row :gutter="20">
						<el-col :span="6">
							<el-form-item label="品牌名称" prop="name">
							  <el-input v-model="addForm.name" autocomplete="off" placeholder="请输入品牌名称"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="状态" prop="status">
							  <el-radio-group v-model="addForm.status">
							    <el-radio :label="true">开启</el-radio>
							    <el-radio :label="false">禁用</el-radio>
							  </el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="排序" prop="sortNum">
							  <el-input v-model="addForm.sortNum" autocomplete="off" placeholder="请输入"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="图片" prop="imgUrl">
							  <el-upload
							    class="avatar-uploader"
							    :action="baseURL + 'common/upload'"
							    :headers="myHeaders"
							    :show-file-list="false"
							    :on-success="uploadSuccess"
							    :before-upload="beforeUpload">
							    <img v-if="addForm.imgUrl" :src="$showImgUrl(addForm.imgUrl)" class="avatar">
							    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
							  </el-upload>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<div slot="footer" class="dialog-footer">
				  <el-button @click="data.removeTab()">取 消</el-button>
				  <el-button type="primary" @click="submitAddForm(data.removeTab)">确 定</el-button>
				</div>
			</div>
		</template>
	</zj-tab-page>
  </div>
</template>

<script>
import { getBrandList, getBrandDetail, saveBrand, deleteBrand } from "@/api/miniapp";
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: {'x-token': getToken()},
      dataList: null, // 列表数据
      listLoading: true, // 列表加载loading

      editId:  null,
      addFormType: 'add',
      addFormVisible: false,
      addForm: {
        name: '', // 名称
        imgUrl: '', // 图片
        status: true,
		sortNum: 0
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
        imgUrl: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
		sortNum: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ],
      },
			formType: 'add',
			formVisible: false,
    }
  },

  created() {
    this.getList();
  },

  methods: {
    getList() {
      getBrandList().then(res => {
        this.dataList = res.data;
        this.listLoading = false;
      })
    },

    // 新增编辑
    addOrEdit(type, id) {
		this.$refs.tabPage.addTab({
			// 对应显示的模块
			activeKey: type,
			// 唯一标识
			key: type,
			// 页签名称
			label: ({ edit: "编辑", add: "新增" })[type],
			// 打开时事件
			triggerEvent: () => {
				this.$nextTick(()=>{
					this.formType = type
					this.formVisible = true
					this.addFormType = type;
					this.addFormVisible = true;
					if(type == 'edit'){
						this.editId = id;
						  getBrandDetail({id: id}).then(res => {
						    this.addForm = {
						      name: res.data.brandName,
						      imgUrl: res.data.imageUrl,
						      status: res.data.status,
						sortNum: res.data.sortNum
						    }
						  })
					}
				})
			},
			// 关闭时事件
			closeEvent: () => {
				this.cancelAddForm()
			}
		})
    },

    // 取消 新增编辑
    cancelAddForm(){
      this.addFormVisible = false;
      this.$refs?.addForm?.resetFields();
      this.selGoodsName = ''
    },

    // 提交 新增编辑
    submitAddForm(cancel) {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let params = {
            brandName: this.addForm.name,
            imageUrl: this.addForm.imgUrl,
            status: this.addForm.status,
			sortNum: this.addForm.sortNum
          }
          if(this.addFormType == 'edit') {
            params.id = this.editId;
          }
          saveBrand(params).then(res => {
            this.cancelAddForm();
			cancel()
            this.getList();
            this.$successMsg('保存成功');
          })
        }
      })
    },

    uploadSuccess(res, file) {
      this.addForm.imgUrl = res.data.url;
    },

    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ['jpg', 'jpeg', 'png'];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$errorMsg('只支持上传jpg/png文件!');
        return false;
      }
    },

    // 操作 - 删除
    handleDelete(id) {
      deleteBrand({id: id}).then(res => {
        this.getList();
        this.$successMsg();
      })
    },
  }
}
</script>

<style scoped lang="scss">

</style>
