<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input
          v-model="queryParams.enterpriseName"
          placeholder="请输入企业名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="燃气成分" prop="component">
        <el-input
          v-model="queryParams.component"
          placeholder="请输入燃气成分"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="运输车辆车牌号" prop="carNumber" label-width="110px">
        <el-input
          v-model="queryParams.carNumber"
          placeholder="请输入运输车辆车牌号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['housingconstruction:gassource:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['housingconstruction:gassource:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['housingconstruction:gassource:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['housingconstruction:gassource:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="gassourceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="企业名称" align="center" prop="enterpriseName"/>
      <el-table-column label="来源地" align="center" prop="address"/>
      <el-table-column label="燃气成分" align="center" prop="component">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.housingconstruction_component" :value="scope.row.component"/>
        </template>
      </el-table-column>
      <el-table-column label="入站时间" align="center" prop="joinInstationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.joinInstationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运输体积" align="center" prop="weight"/>
      <el-table-column label="运输车辆车牌号" align="center" prop="carNumber" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['housingconstruction:gassource:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['housingconstruction:gassource:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改气源数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1300px" append-to-body class="form-style">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="所属企业" prop="enterpriseId">
              <el-select v-model="form.enterpriseId" placeholder="请选择所属企业" @change="handleEnterpriseChange">
                <el-option
                  v-for="data in enterpriseList"
                  :key="data.id"
                  :label="data.enterpriseName"
                  :value="data.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源地" prop="address">
              <el-input v-model="form.address" placeholder="请输入来源地"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="燃气成分" prop="component">
              <el-select v-model="form.component" placeholder="请选择燃气成分">
                <el-option
                  v-for="dict in dict.type.housingconstruction_component"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入站时间" prop="joinInstationTime">
              <el-date-picker clearable size="small"
                              v-model="form.joinInstationTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择入站时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="运输车辆" prop="carId">
              <el-select v-model="form.carId" filterable placeholder="请选择运输车辆"  @change="handleCarChange">
                <el-option
                  v-for="data in carList"
                  :key="data.id"
                  :label="data.carNumber"
                  :value="data.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运输体积" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入运输体积"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" multiple:false :show-count="true"
                          placeholder="请选择部门" @select="hx" :noResultsText="'空'" :noOptionsText="'空'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-form-item label="危化品检测报告" prop="fileUrl"  label-width="130px">
            <fileUpload v-model="form.fileUrl" :setFileName="setFileName" :removeFileName="removeFileName"></fileUpload>
          </el-form-item>
        </el-row>
        <el-row :gutter="24">
          <el-form-item label="危化品运输车辆许可" prop="attachPaths" label-width="160px">
            <ImageUpload v-model="form.attachPaths" ref="ImageUpload" :fileType="['png', 'jpg', 'jpeg']" :value="form.attachPaths" @input="getUrl" :limit="10"></ImageUpload>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addGassource,
  delGassource,
  getGassource,
  listGassource,
  updateGassource
} from "@/api/data/housingconstruction/gassource";
import {getListAll} from "@/api/data/housingconstruction/enterprise";
import deptselector from "@/views/components/deptselector.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {treeselect} from "@/api/system/dept";
import {getCarList} from "@/api/data/housingconstruction/car";
import DataImageUpload from "@/components/ImageUpload/dataUpload.vue";
import FileUpload from '@/views/components/FileUpload/index.vue'

export default {
  name: "Gassource",
  components: {DataImageUpload, deptselector, Treeselect, FileUpload},
  dicts: ['housingconstruction_component'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      fileNames: [],
      // 总条数
      total: 0,
      // 气源数据表格数据
      gassourceList: [],
      //企业信息列表
      enterpriseList: [],
      // 部门树选项
      deptOptions: [],
      //车辆列表
      carList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        enterpriseName: null,
        address: null,
        component: null,
        joinInstationTime: null,
        weight: null,
        carNumber: null
      },
      // 表单参数
      form: {
        fileUrl: '',
        fileName: '',
        fileUrlList: [],
        fileNameList: []
      },
      // 表单校验
      rules: {
        enterpriseId: [
          {required: true, message: "企业不能为空", trigger: "blur"}
        ],
        address: [
          {required: true, message: "来源地不能为空", trigger: "blur"}
        ],
        component: [
          {required: true, message: "燃气成分不能为空", trigger: "blur"}
        ],
        joinInstationTime: [
          {required: true, message: "入站时间不能为空", trigger: "blur"}
        ],
        weight: [
          {required: true, message: "运输体积不能为空", trigger: "blur"}
        ],
        carId: [
          {required: true, message: "运输车辆不能为空", trigger: "blur"}
        ],
        deptId: [
          {required: true, message: "所属部门不能为空", trigger: "blur"}
        ],
        fileUrl: [
          {required: true, message: "危化品检测报告不能为空", trigger: "blur"}
        ],
        attachPaths: [
          {required: true, message: "危化品运输车车辆许可不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getEnterpriseList();
    this.getCarList();
  },
  methods: {
    /** 附件:图片 **/
    getUrl(url) {
      //获取图片全路径  例：http://{{ ip }}:{{ port }}/group1/M00/00/07/wKgKEGVxMCiAZbvVAAJE9SGvagw915.jpg
      this.form.attachPaths = url
      //获取图片路径  例：group1/M00/00/07/wKgKEGVxL6eACFv2AAJE9SGvagw622.jpg
      // this.form.attachPaths = this.$refs.ImageUpload.dialogName
    },
    /** 附件:文件 **/
    setFileName(fileName) {
      let that = this
      that.fileNames.push(fileName)
    },
    removeFileName(index) {
      let that = this
      that.fileNames.splice(index, 1);
      let fileurls = that.form.fileUrl.split(",")
      fileurls.splice(index, 1)
      that.form.fileUrl = fileurls.toString()
    },
    /** 获取车辆列表 **/
    getCarList(){
      getCarList().then(res=>{
        this.carList = res.data;
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    hx(node) {
      this.form.dataDeptId = node.id
      this.form.deptId = node.id
      this.form.deptName = node.label
      this.$refs.form.validateField("deptId")
    },
    handleEnterpriseChange(newId) {
      const selectedEnterprise = this.enterpriseList.find(item => item.id === newId);
      if (selectedEnterprise) {
        this.form.enterpriseName = selectedEnterprise.enterpriseName;
      } else {
        this.form.enterpriseName = '';
      }
    },
    handleCarChange(newId){
      const selectedCar = this.carList.find(item => item.id === newId);
      if (selectedCar) {
        this.form.carNumber = selectedCar.carNumber;
      } else {
        this.form.carNumber = '';
      }
    },
    getEnterpriseList(){
      getListAll().then(res=>{
        this.enterpriseList = res.data
      })
    },
    /** 查询气源数据列表 */
    getList() {
      this.loading = true;
      listGassource(this.queryParams).then(response => {
        this.gassourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createName: null,
        createTime: null,
        updateBy: null,
        updateName: null,
        updateTime: null,
        deptId: null,
        deptName: null,
        enterpriseId: null,
        enterpriseName: null,
        address: null,
        component: null,
        joinInstationTime: null,
        weight: null,
        carNumber: null
      };
      this.fileNames = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加气源数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGassource(id).then(response => {
        const list = response.data.fileUrl.split(',');
        if (response.data.fileUrl != "") {
          for (var a = 0; a < list.length; a++) {
            let listurl = list[a].split('+')
            this.fileNames.push(listurl[1])
          }
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改气源数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.fileName = this.fileNames.toString()
          if (this.form.id != null) {
            updateGassource(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.fileNames = [];
              this.open = false;
              this.getList();
            });
          } else {
            addGassource(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.fileNames = [];
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除气源数据编号为"' + ids + '"的数据项？').then(function () {
        return delGassource(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sooka-sponest-center-data/gassource/export', {
        ...this.queryParams
      }, `气源数据_${format_date(new Date())}.xlsx`)
    }
  }
};
</script>
