<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">    
      
      <el-form-item label="项目" prop="projectId">
        <el-select :disabled="data.currentProId != ''" v-model="queryParams.projectId" placeholder="请选择项目" clearable style="width:150px;"
          @change="handleQuery">
          <el-option v-for="prj in data.projects" :key="prj.id" :label="prj.projectName" :value="prj.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="碳因子类型" prop="carbonFactorType">
        <el-select v-model="queryParams.carbonFactorType" style="width: 120px;" clearable>         
          <el-option v-for="(it,idx) in data.types" :key="idx" :label="it.text" :value="it.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="carbonName">
        <el-input v-model="queryParams.carbonName" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @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="Plus" @click="handleAdd"
          v-hasPermi="['manage:greenCarbonItem:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="false">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:greenCarbonItem:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:greenCarbonItem:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">       
          <el-upload ref="uploadRef" :limit="1" accept=".xlsx" :headers="upload.headers" v-hasPermi="['manage:greenCarbonItem:import']"
            :action="upload.url" :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="true">
            <el-button type="primary" v-loading="upload.isUploading" >导入</el-button>
        </el-upload>    
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:greenCarbonItem:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="greenCarbonItemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公司" align="center" prop="compName" v-if="!data.currentProId"/>
      <el-table-column label="分包单位" align="center" prop="projectName"  v-if="!data.currentProId"/>
      <el-table-column label="碳因子类型" align="center" prop="carbonFactorType">
        <template #default="scope">{{getGreenCarbon(scope.row.carbonFactorType).text }}</template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="carbonName" />
      <el-table-column label="单位" align="center" prop="unit">
        <template #default="scope">kg CO2/{{scope.row.unit}}</template>
      </el-table-column>
      <el-table-column label="碳排放因子" align="center" prop="carbonFactor" />     
      <el-table-column label="创建人" align="center" prop="createBy" />     
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</template>
      </el-table-column>   
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:greenCarbonItem:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:greenCarbonItem:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改碳因子管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="greenCarbonItemRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="碳因子类型" prop="carbonFactorType">
          <el-select v-model="form.carbonFactorType"  clearable>         
          <el-option v-for="(it,idx) in data.types" :key="idx" :label="it.text" :value="it.value"></el-option>
        </el-select>
        </el-form-item>       
        <el-row>
          <el-col :span="14">
            <el-form-item label="名称" prop="carbonName">
          <el-input v-model="form.carbonName" placeholder="请输入名称" />
        </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
          </el-col>
        </el-row> 
        <el-form-item label="碳排放因子" prop="carbonFactor">
          <el-input v-model="form.carbonFactor" placeholder="请输入碳排放因子" style="width:calc(100% - 120px);"/>
          <span style="margin-left:4px;">kg CO2/{{ form.unit }}</span>
        </el-form-item>        
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: center;">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="导入结果" v-model="data.openImport" width="800px"  append-to-body class="green-import-result-dialog">
      <el-table  :data="data.importData" height="50vh">
      <el-table-column label="公司" align="center" prop="compName" v-if="!data.currentProId"/>
      <el-table-column label="分包单位" align="center" prop="projectName"  v-if="!data.currentProId"/>
      <el-table-column label="碳因子类型" align="center" prop="carbonFactorType">
        <template #default="scope">{{getGreenCarbon(scope.row.carbonFactorType).text }}</template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="carbonName" />
      <el-table-column label="单位" align="center" prop="unit">
        <template #default="scope">kg CO2/{{scope.row.unit}}</template>
      </el-table-column>
      <el-table-column label="碳排放因子" align="center" prop="carbonFactor" />   
      <el-table-column label="结果" align="center" >
        <template #default="scope">
          <span :class="(scope.row.remark||'').indexOf('成功')>=0?'fgreen':'fred'">{{scope.row.remark}}</span>
        </template>
      </el-table-column> 
    </el-table>
      <template #footer>
        <div class="dialog-footer" style="text-align: center;">
          <el-button type="primary" @click="open=false">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GreenCarbonItem">
import { getToken } from "@/utils/auth";
import { findMyProjectList } from "@/api/publics";
import { listGreenCarbonItem, getGreenCarbonItem, delGreenCarbonItem, addGreenCarbonItem, updateGreenCarbonItem } from "@/api/manage/greenCarbonItem";
import greenCarbonData,{getGreenCarbon} from "./greenCarbonData";
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance();
const userStore = useUserStore()
const greenCarbonItemList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
/*** 用户导入参数 */
const upload = reactive({
   // 是否显示弹出层（用户导入）
   open: false,
   // 弹出层标题（用户导入）
   title: "",
   // 是否禁用上传
   isUploading: false,
   // 是否更新已经存在的用户数据
   updateSupport: 0,
   // 设置上传的请求头部
   headers: { Authorization: "Bearer " + getToken() },
   // 上传的地址
   url: import.meta.env.VITE_APP_BASE_API + "/manage/greenCarbonItem/import"
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    comId: null,
    projectId: null,
    carbonFactorType: null,
    carbonName: null,
    unit: null,
    carbonFactor: null,
    state: null,
    isDel: null,
  },
  rules: {
    carbonFactorType: [
      { required: true, message: '请选择碳因子类型', trigger: 'change' },
    ],
    carbonName: [
      { required: true, message: '请输入名称', trigger: 'blur' },
    ],
    unit: [
      { required: true, message: '请输入单位', trigger: 'blur' },
    ],
    carbonFactor: [
      { required: true, message: '请输入碳排放因子', trigger: 'blur' },
    ],
  },
  projects:[],
  currentProId:'',
  types:greenCarbonData.types,
  delDatas:[],
  importData:[],
  openImport:false,
});

const { queryParams, form, rules } = toRefs(data);
/** 查询项目列表 */
function getProjectList() {
  findMyProjectList({ pageNum: 1, pageSize: 100 }).then(response => {
    data.projects = response.rows;
    if (userStore.currentProId) {
      queryParams.value.projectId = userStore.currentProId
      data.currentProId = userStore.currentProId;
    }
  });
}
/** 查询碳因子管理列表 */
function getList() {
  loading.value = true;
  listGreenCarbonItem(queryParams.value).then(response => {
    greenCarbonItemList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    comId: null,
    projectId: null,
    carbonFactorType: null,
    carbonName: null,
    unit: null,
    carbonFactor: null,
    state: null,
    remark: null,
    isDel: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("greenCarbonItemRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  data.delDatas=selection.map(item=> getGreenCarbon(item.carbonFactorType).text +' - '+item.carbonName);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  if (!userStore.currentProId) {
    proxy.$modal.msgWarning("请切换到项目数据！！！");
    return false;
  }
  reset();
  form.value.projectId = userStore.currentProId;
  form.value.projectName = userStore.currentProName;
  open.value = true;
  title.value = "碳因子管理-增加";
}

/** 修改按钮操作 */
function handleUpdate(row) {  
  reset();
  const _id = row.id || ids.value
  getGreenCarbonItem(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "碳因子管理-修改";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["greenCarbonItemRef"].validate(valid => {
    if (valid) {
      form.value.comId=userStore.currentComId;
      if (form.value.id != null) {
        updateGreenCarbonItem(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGreenCarbonItem(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids =row && row.id? getGreenCarbon(row.carbonFactorType).text +' - '+row.carbonName:data.delDatas.join(",");
  proxy.$modal.confirm('是否确认删【' + _ids + '】的数据项？').then(function () {
    return delGreenCarbonItem(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/greenCarbonItem/export', {
    ...queryParams.value
  }, `greenCarbonItem_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
   upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {  
   upload.isUploading = false;
   if(response.code==200){
    proxy.$modal.msgSuccess("导入成功!");
    data.importData=response.data||[];
    data.openImport=true;
   }else{
    proxy.$modal.msgError("导入失败!");
   }
   if(fileList.length>0){
    fileList.splice(0,1)
   }
};


getList();
getProjectList();
</script>
<style type="scss">

</style>