<template>
  <div class="app-container">
    <!-- 筛选条件 -->
    <div class="screen-container">
      <el-form ref="screenForm" :model="screenForm" label-width="70px" size="small" label-position="left">
        <div style="margin-bottom: 20px">
          <el-radio-group v-model="screenForm.status" size="medium" @change="submitScreenForm">
            <el-radio-button :label="''">全部</el-radio-button>
            <el-radio-button :label="true">开启</el-radio-button>
            <el-radio-button :label="false">禁用</el-radio-button>
          </el-radio-group>
        </div>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="服务品牌" prop="brand">
              <el-select v-model="screenForm.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-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="一级分类" prop="mainId">
              <el-select v-model="screenForm.mainId" placeholder="请选择一级分类" clearable>
                <el-option
                  v-for="item in screenMainList"
                  :key="item.categoryId"
                  :label="item.name"
                  :value="item.categoryId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="二级分类" prop="smallId">
              <el-select v-model="screenForm.smallId" placeholder="请选择二级分类" clearable :disabled="!screenForm.mainId">
                <el-option
                  v-for="item in screenSmallList"
                  :key="item.categoryId"
                  :label="item.name"
                  :value="item.categoryId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="故障内容" prop="content">
              <el-input v-model="screenForm.content" placeholder="请输入故障内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24" class="tr">
            <el-form-item label="">
              <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
              <el-button size="small" @click="resetScreenForm">清空</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <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>

          <el-button size="small" type="warning" @click="handleExport">导出</el-button>

          <el-upload
            class="import-btn"
            style="display: inline-block; margin: 0 10px;"
            :action="baseURL + 'student/import'"
            :http-request="handleImport"
            :file-list="importFileList"
          >
            <el-button size="small" type="warning" :loading="importLoading">{{ importLoading ? '导入中...' : '导入' }}</el-button>
          </el-upload>

          <el-button size="small" @click="handleDownload">下载导入模板</el-button>

          <span style="font-size: 12px; margin-left: 10px; color: #ebb563; font-weight: 500;">注：同一品牌、一级分类、二级分类、故障内容有多条故障排除指引时，要分开导入维护</span>
        </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="120"></el-table-column>
          <el-table-column align="center" label="一级分类" prop="oneCategoryName" min-width="120"></el-table-column>
          <el-table-column align="center" label="二级分类" prop="twoCategoryName" min-width="120"></el-table-column>
          <el-table-column align="center" label="故障内容" prop="content1" min-width="180"></el-table-column>
          <el-table-column align="center" label="故障排除指引" prop="content2" min-width="300">
            <template slot-scope="scope">
              <el-popover
                placement="right-start"
                :title="scope.row.content1"
                width="300"
                trigger="click"
                :content="scope.row.content2">
                <el-link type="primary" slot="reference" class="ellipsis" style="display: block">{{scope.row.content2}}</el-link>
              </el-popover>
            </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="right" label-width="110px">
        <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="content1">
          <el-input v-model="addForm.content1" placeholder="请输入故障内容"></el-input>
        </el-form-item>
        <el-form-item label="故障排除指引" prop="content2">
          <el-input v-model="addForm.content2" placeholder="请输入故障排除指引" type="textarea" :rows="6"></el-input>
        </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, getBrandList } from "@/api/miniapp";
import { getClassifyList } from '@/api/goods'
import { getToken } from '@/utils/auth'
import { downloadFiles, handleImport } from '@/utils/util'

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, // 列表总数

      screenForm: { // 筛选表单数据
        status: '', // 状态
        brand: '', // 服务品牌
        mainId: '', // 一级分类
        smallId: '', // 二级分类
        content: '', // 故障内容
      },
      screenMainList: [], // 一级分类列表
      screenSmallList: [], // 二级分类列表

      editId:  null,
      addFormType: 'add',
      addFormVisible: false,
      addForm: {
        brand: '',
        mainId: '',
        smallId: '',
        content1: '',
        content2: '',
        status: true,
      },
      addFormRules: {
        brand: [
          { required: true, message: '请选择服务品牌', trigger: 'change' }
        ],
        mainId: [
          { required: true, message: '请选择一级分类', trigger: 'change' }
        ],
        smallId: [
          { required: true, message: '请选择二级分类', trigger: 'change' }
        ],
        content1: [
          { required: true, message: '请输入故障内容', trigger: 'blur' }
        ],
        content2: [
          { required: true, message: '请输入故障排除指引', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
      },

      brandList: [], // 品牌列表
      mainList: [], // 一级分类列表
      smallList: [], // 二级分类列表

      importLoading: false, // 导入加载loading
      importFileList: [], // 导入列表
    }
  },

  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,
    },
    'screenForm.mainId': {
      handler(newValue, oldValue) {
        this.screenForm.smallId = '';
        if(newValue) {
          let item = this.screenMainList.find(item => {
            return item.categoryId == this.screenForm.mainId;
          })
          this.screenSmallList = item.children;
        }
      },
      immediate: true,
    },
  },

  created() {
    this.getList();

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

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

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

    getList() {
      let params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        type: 2,
        brandId: this.screenForm.brand,
        oneCategoryId: this.screenForm.mainId,
        twoCategoryId: this.screenForm.smallId,
        content1: this.screenForm.content,
        status: this.screenForm.status,
      }

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

     // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1;
      this.getList();
    },
    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields();
      this.currentPage = 1;
      this.getList();
    },

    // 更改每页数量
    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 = {
            brand: res.data.brandId,
            mainId: res.data.oneCategoryId,
            smallId: res.data.twoCategoryId,
            content1: res.data.content1,
            content2: res.data.content2,
            status: res.data.status,
          }
        })
      }
    },

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

    // 提交 新增编辑
    submitAddForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let params = {
            type: 2,
            brandId: this.addForm.brand,
            oneCategoryId: this.addForm.mainId,
            twoCategoryId: this.addForm.smallId,
            content1: this.addForm.content1,
            content2: this.addForm.content2,
            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();
      })
    },

    // 导入
    async handleImport(param) {
      this.importLoading = true;
      const file = param.file;
      const formData = new FormData();
      formData.append("file", file);
      let result = await handleImport('charging/standard/import', formData);
      this.importLoading = false;
      this.importFileList = [];
      if(result.code == 200) {
        this.$alert(result.message, '导入成功', {
          confirmButtonText: '确定'
        });
        this.getList();
      }else {
        this.$alert(result.message, '导入失败', {
          confirmButtonText: '确定'
        });
      }
    },

    // 下载导入模版
    handleDownload() {
      downloadFiles('charging/standard/download');
    },

    // 导出
    handleExport() {
      let screenData = {
        type: 2,
        brandId: this.screenForm.brand,
        oneCategoryId: this.screenForm.mainId,
        twoCategoryId: this.screenForm.smallId,
        content1: this.screenForm.content,
        status: this.screenForm.status,
      };
      downloadFiles('charging/standard/exportData', screenData);
    },
  }
}
</script>

<style scoped lang="scss">

</style>