<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="head-container">
          <el-input v-model="searchName" placeholder="请输入驾校名称" clearable prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>
        <div class="head-container" style="max-height: 700px;overflow-y: auto">
          <el-tree ref="tree" :data="schoolOption.filter(item => item.label.includes(searchName))" accordion node-key="id" :default-expanded-keys="selectNodes.map(item => item.id)" @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="18">
        <el-row :gutter="20">
          <el-form ref="queryForm" :model="queryParams" :inline="true">
            <el-form-item>
              <el-input v-model="queryParams.typeName" placeholder="请输入班型名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-select v-model="queryParams.licenseType" clearable placeholder="选择驾照类型">
                <el-option v-for="item in licenseTypeOption" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="queryParams.status" placeholder="班型状态" clearable>
                <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
              <el-button v-hasPermi="['sch:classType:add']" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
              <el-button v-hasPermi="['sch:classType:remove']" type="danger" icon="el-icon-delete" :disabled="multiple" @click="handleDelete">删除</el-button>
              <el-button v-hasPermi="['sch:classType:clone']" type="primary" icon="el-icon-copy" :disabled="multiple" @click="handleClone">克隆</el-button>

            </el-form-item>
          </el-form>
        </el-row>

        <el-table v-loading="loading.tableLoading" :data="tableDataList" stripe border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />

          <el-table-column type="index" width="50" />
          <el-table-column label="驾校" prop="schoolName" />
          <el-table-column label="场地" prop="placeName" />
          <el-table-column label="班型名称" prop="typeName" />
          <el-table-column label="驾照类型" prop="licenseType" :formatter="licenseTypeFormat" width="80" />
          <!-- <el-table-column label="原价"  prop="originalPrice"  /> -->
          <el-table-column label="报价" prop="currentPrice" width="60" />
          <el-table-column label="底价" prop="minPrice" width="60" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="状态" prop="status" :formatter="statusFormat" width="80" />
          <el-table-column label="创建时间" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="130">
            <template slot-scope="scope">
              <el-button v-hasPermi="['sch:classType:edit']" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button v-hasPermi="['sch:classType:remove']" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>

            </template>
          </el-table-column>
        </el-table>

        <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getPageList" />
      </el-col>
    </el-row>

    <el-dialog title="班型设置" :visible.sync="modalVisible" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="modalForm" :model="modalForm" :rules="modalRules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="驾校">
              <el-input v-model="modalForm.schoolName" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="场地">
              <el-input v-model="modalForm.placeName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="班型名称" prop="typeName">
              <el-input v-model="modalForm.typeName" placeholder="请输入班型名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驾照类型" prop="licenseType">
              <el-select v-model="modalForm.licenseType" placeholder="选择驾照类型">
                <el-option v-for="item in licenseTypeOption" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="报价" prop="currentPrice">
              <el-input v-model="modalForm.currentPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="底价" prop="minPrice">
              <el-input v-model="modalForm.minPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="甩单低价" prop="orderMinPrice">
              <el-input v-model="modalForm.orderMinPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入账低价" prop="enterMinPrice">
              <el-input v-model="modalForm.enterMinPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司低价" prop="companyMinPrice">
              <el-input v-model="modalForm.companyMinPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工低价" prop="employeeMinPrice">
              <el-input v-model="modalForm.employeeMinPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="orderNum">
              <el-input v-model="modalForm.orderNum" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="currentPrice">
              <el-radio-group v-model="modalForm.status">
                <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="是否克隆到场地" prop="currentPrice">
              <el-radio-group v-model="modalForm.clone">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <span>克隆到场地，该班型则不统一管理</span>
          </el-col>
        </el-row> -->
        <el-row>
          <el-form-item label="描述" prop="description">
            <el-input v-model="modalForm.description" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入描述" />
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer">
        <el-button @click="modalVisible = false">取 消</el-button>
        <el-button v-loading="loading.modalSaveLoading" type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="克隆班型" :visible.sync="cloneOpen" width="780px" append-to-body :v-loading="loading.cloneLoading">
      <el-form ref="clonForm" :model="clonForm" :rules="modalRules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="场地" prop="placeIdList">
              <el-select v-model="clonForm.placeIds" placeholder="请选择" size="small" multiple filterable clearable>
                <el-option v-for="dict in placeOption" :key="dict.placeId" :label="dict.name" :value="dict.placeId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="padding-top:20px">
        <el-button type="primary" @click="cloneSave">确 定</el-button>
        <el-button @click="cloneOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getClassTypeTableList, updateClassType, insertClassType, deleteClassType, cloneClassType } from '@/api/sch/classType';
import { validateMoney } from '@/utils/validate';
import { getMapData } from '@/api/sch/place';

export default {
  name: 'Classtype',
  data() {
    return {
      searchName: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeName: undefined,
        status: undefined,
        schoolId: this.$store.getters.schoolId,
        licenseType: undefined
      },
      loading: {
        tableLoading: false,
        modalSaveLoading: false,
        cloneLoading: false
      },
      tableDataList: [],
      total: 0,
      statusOptions: [],
      licenseTypeOption: [],
      modalVisible: false,
      modalForm: {},
      modalRules: {
        typeName: {
          required: true,
          message: '班型名称不为空',
          trigger: 'blur'
        },
        originalPrice: {
          required: true,
          validator: validateMoney,
          trigger: 'blur'
        },
        currentPrice: {
          required: true,
          validator: validateMoney,
          trigger: 'blur'
        },
        minPrice: { required: true, validator: validateMoney, trigger: 'blur' },
        placeIds: {
          required: true,
          message: '场地不为空',
          trigger: 'change'
        }
      },
      schoolOption: [],
      placeOption: [],
      selectNodes: [],
      multiple: true,
      single: true,
      cloneOpen: false,
      clonForm: {}
    };
  },
  created() {
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts('license_type').then((response) => {
      this.licenseTypeOption = response.data;
    });
    this._getSchoolTree();
    this.getPageList();

    this.deptId = this.$store.getters.schoolId;
  },
  methods: {
    // 搜索
    handleQuery() {
      this.queryParams.page = 1;
      this.getPageList();
    },
    getPageList() {
      this.loading.tableLoading = true;
      const params = {
        ...this.queryParams,
        schoolId: this.selectNodes.length > 0 ? this.selectNodes[0].id : undefined,
        placeId: this.selectNodes.length == 2 ? this.selectNodes[1].id : undefined
      };
      this.tableDataList = [];
      getClassTypeTableList(params).then((response) => {
        this.tableDataList = response.rows;
        this.total = response.total;
        this.loading.tableLoading = false;
      });
    },
    // 重置搜索
    resetQuery() {
      this.queryParams.typeName = '';
      this.queryParams.status = undefined;
      this.queryParams.schoolId = undefined;
      this.queryParams.placeId = undefined;
      this.queryParams.licenseType = undefined;
      this.handleQuery();
    },
    // 查询驾校
    _getSchoolTree() {
      getMapData().then((resp) => {
        if (resp.code == 200) {
          let sList = resp.data.schoolList.filter((item) => item.showInMap);
          const pList = resp.data.placeList.filter((item) => item.showInMap);
          sList = sList.map((item) => ({
            id: item.schoolId,
            label: item.schoolName,
            level: 1,
            children: pList
              .filter((place) => item.schoolId === place.schoolId)
              .map((place) => ({
                id: place.placeId,
                label: place.name,
                level: 2
              }))
          }));
          this.schoolOption = sList;
          this.placeOption = resp.data.placeList;
        }
      });
    },
    // 新增
    handleAdd() {
      if (this.selectNodes.length < 1) {
        this.msgError('请选择左侧驾校或场地');
        return;
      }
      this.resetForm('modalForm');
      this.modalVisible = true;
      this.modalForm = {
        typeName: '',
        status: '0',
        originalPrice: undefined,
        licenseType: 'C1',
        description: '',
        currentPrice: undefined,
        typeId: undefined,
        schoolId: this.selectNodes[0].id,
        schoolName: this.selectNodes[0].name,
        clone: false,
        orderMinPrice: undefined,
        enterMinPrice: undefined,
        companyMinPrice: undefined,
        employeeMinPrice: undefined
      };

      if (this.selectNodes.length > 1) {
        this.$set(this.modalForm, 'placeId', this.selectNodes[1].id);
        this.$set(this.modalForm, 'placeName', this.selectNodes[1].name);
      }
    },
    // 编辑
    handleUpdate(listItem) {
      this.resetForm('modalForm');
      this.modalForm = {
        ...listItem
      };
      if (listItem.placeId) {
        this.$set(this.modalForm, 'placeName', this.placeOption.find((item) => item.placeId == listItem.placeId).name);
      }
      this.modalVisible = true;
    },
    //  模态框保存
    handleSave() {
      this.$refs.modalForm.validate((valid) => {
        if (valid) {
          this.loading.modalSaveLoading = true;
          if (this.modalForm.typeId) {
            updateClassType(this.modalForm).then((resp) => {
              if (resp.code === 200) {
                this.$message.success('修改成功');
                this.modalVisible = false;
                this.loading.modalSaveLoading = false;
                this.getPageList();
              } else {
                this.$message.error('修改失败:' + resp.message);
                this.loading.modalSaveLoading = false;
              }
            });
          } else {
            if (!this.modalForm.schoolId) {
              this.$set(this.modalForm, 'schoolId', this.$store.getters.schoolId);
            }

            insertClassType(this.modalForm).then((resp) => {
              if (resp.code === 200) {
                this.$message.success('新增成功');
                this.modalVisible = false;
                this.loading.modalSaveLoading = false;
                this.getPageList();
              } else {
                this.$message.error('新增失败:' + resp.message);
                this.loading.modalSaveLoading = false;
              }
            });
          }
        }
      });
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 字典状态字典翻译
    placeFormat(row, column) {
      if (row.placeId) {
        return this.placeOption.length > 0 ? this.placeOption.find((item) => item.placeId == row.placeId).name : '';
      }
    },
    // 字典状态字典翻译
    licenseTypeFormat(row, column) {
      return this.selectDictLabel(this.licenseTypeOption, row.licenseType);
    },
    handleNodeClick(data, node) {
      if (data.level === 1) {
        this.selectNodes = [{ id: data.id, name: data.label }];
      } else {
        this.selectNodes = [
          { id: node.parent.data.id, name: node.parent.data.label },
          { id: data.id, name: data.label }
        ];
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.typeId);
      this.nos = selection.map((item) => item.productNo);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(item) {
      const typeId = item.typeId || this.ids;

      this.$confirm('是否确认删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then((res) => {
          deleteClassType(typeId).then((resp) => {
            if (resp.code === 200) {
              this.$message.success('删除成功');
              this.getPageList();
            }
          });
        })
        .catch(function () {});
    },
    handleClone() {
      this.cloneOpen = true;
      this.clonForm = {
        typeIds: this.ids,
        placeIds: undefined
      };
    },
    cloneSave() {
      this.$refs.clonForm.validate((valid) => {
        if (valid) {
          this.loading.cloneLoading = true;
          cloneClassType(this.clonForm).then((resp) => {
            if (resp.code === 200) {
              this.$message.success('克隆成功');
              this.cloneOpen = false;
              this.getPageList();
            }
            this.loading.cloneLoading = false;
          });
        }
      });
    }
  }
};
</script>
