<template>
  <div class="app-container">
    <div class="mymain-container">
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button 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="typeName" min-width="180"></el-table-column>
          <el-table-column align="center" label="服务品牌" prop="brandName" min-width="180"></el-table-column>
          <el-table-column align="center" label="一级分类" prop="oneCategoryName" min-width="180"></el-table-column>
          <el-table-column align="center" label="二级分类" prop="twoCategoryName" 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="scope.row.imageUrl" :preview-src-list="[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="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" @click="addOrEdit('edit', scope.row.id)">编辑</el-button>
              <el-popconfirm style="margin-left: 10px;" title="确定删除吗？" @onConfirm="handleDelete(scope.row.id)">
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </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>
    </div>


    <!-- 新增编辑 -->
    <el-dialog :title="addFormType === 'add' ? '新增收费标准':'编辑收费标准'" :visible.sync="addFormVisible" :show-close="false" width="50%" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="left" label-width="80px">
        <el-form-item label="业务类型" prop="businessType">
          <el-select v-model="addForm.businessType" placeholder="请选择业务类型" clearable>
            <el-option
              v-for="item in businessTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务品牌" prop="brand">
          <el-select v-model="addForm.brand" placeholder="请选择服务品牌" clearable>
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.brandName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="一级分类" prop="mainId">
          <el-select v-model="addForm.mainId" placeholder="请选择一级分类" clearable>
            <el-option
              v-for="item in mainList"
              :key="item.categoryId"
              :label="item.name"
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" prop="smallId">
          <el-select v-model="addForm.smallId" placeholder="请选择二级分类" clearable :disabled="!addForm.mainId">
            <el-option
              v-for="item in smallList"
              :key="item.categoryId"
              :label="item.name"
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>
        <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="addForm.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <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-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddForm">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMainList, getMainDetail, saveMain, deleteMain, getTypeList, getBrandList } from "@/api/miniapp";
import { getClassifyList } from '@/api/goods'
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
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数

      editId:  null,
      addFormType: 'add',
      addFormVisible: false,
      addForm: {
        businessType: '',
        brand: '',
        mainId: '',
        smallId: '',
        imgUrl: '',
        status: true,
      },
      addFormRules: {
        businessType: [
          { required: true, message: '请选择业务类型', trigger: 'change' }
        ],
        brand: [
          { required: true, message: '请选择服务品牌', trigger: 'change' }
        ],
        mainId: [
          { required: true, message: '请选择一级分类', trigger: 'change' }
        ],
        smallId: [
          { required: true, message: '请选择二级分类', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
        imgUrl: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
      },

      businessTypeList: [], // 业务类型列表
      brandList: [], // 品牌列表
      mainList: [], // 一级分类列表
      smallList: [], // 二级分类列表
    }
  },

  watch: {
    'addForm.mainId': {
      handler(newValue, oldValue) {
        if(newValue) {
          let item = this.mainList.find(item => {
            return item.categoryId == this.addForm.mainId;
          })
          this.smallList = item.children;
        }
      },
      immediate: true,
    },
  },

  created() {
    this.getList();

    this.getTypeList();
    this.getBrandList();
    this.getClassifyList();
  },

  methods: {
    // 获取业务类型列表
    getTypeList() {
      getTypeList().then(res => {
        this.businessTypeList = res.data;
      })
    },

    // 获取业务类型列表
    getBrandList() {
      getBrandList().then(res => {
        this.brandList = res.data;
      })
    },

    // 获取分类列表
    getClassifyList() {
      getClassifyList({
        type: 2,
        name: '',
      }).then(res => {
        this.mainList = res.data;
      })
    },

    getList() {
      let params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        type: 1
      }

      getMainList(params).then(res => {
        this.dataList = res.data.records;
        this.listTotal = res.data.total;
        this.listLoading = false;
      })
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getList()
    },
    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 新增编辑
    addOrEdit(type, id) {
      this.addFormType = type;
      this.addFormVisible = true;
      if(type == 'edit') {
        this.editId = id;
        getMainDetail({id}).then(res => {
          this.addForm = {
            businessType: res.data.chargingStandardTypeId,
            brand: res.data.brandId,
            mainId: res.data.oneCategoryId,
            smallId: res.data.twoCategoryId,
            imgUrl: res.data.imageUrl,
            status: res.data.status,
          }
        })
      }
    },

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

    // 提交 新增编辑
    submitAddForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let params = {
            type: 1,
            chargingStandardTypeId: this.addForm.businessType,
            brandId: this.addForm.brand,
            oneCategoryId: this.addForm.mainId,
            twoCategoryId: this.addForm.smallId,
            imageUrl: this.addForm.imgUrl,
            status: this.addForm.status,
          }
          if(this.addFormType == 'edit') {
            params.id = this.editId;
          }
          saveMain(params).then(res => {
            this.cancelAddForm();
            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) {
      deleteMain({id: id}).then(res => {
        this.getList();
        this.$successMsg();
      })
    },
  }
}
</script>

<style scoped lang="scss">

</style>