<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="projectStatus">
        <el-input
          v-model="queryParams.projectStatus"
          placeholder="请输入状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申报开始日期" prop="projectAppStTime" label-width="140px">
        <el-date-picker clearable
          v-model="queryParams.projectAppStTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择申报开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="申报结束日期" prop="projectAppEndTime" label-width="140px">
        <el-date-picker clearable
          v-model="queryParams.projectAppEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择申报结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="项目负责人" prop="projectLeader" label-width="140px">
        <el-input
          v-model="queryParams.projectLeader"
          placeholder="请输入项目负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="项目预算(万)" prop="projectBudget" label-width="100px">
        <el-input
          v-model="queryParams.projectBudget"
          placeholder="请输入项目预算(万)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目负责人联系电话" prop="projectLeaderPhone" label-width="140px">
        <el-input
          v-model="queryParams.projectLeaderPhone"
          placeholder="请输入联系电话"
          clearable
          @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="['scientific:application: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="['scientific:application: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="['scientific:application: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="['scientific:application:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <!-- <el-table-column label="项目ID" align="center" prop="projectId" v-if="true" width="180"/> -->
      <el-table-column label="项目名称" align="center" :min-width="280">
        <template slot-scope="scope">
          <el-tag size="medium">{{ scope.row.projectName }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="项目负责人" align="center" prop="projectLeader" width="100"/>
      <el-table-column label="申报状态" align="center" width="100px" :min-width="100">
        <template slot-scope="scope">
          <el-tag size="medium" :type="getTagType(scope.row.projectDeclareStatus)">
            {{ formatProjectDeclareStatus(scope.row.projectDeclareStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="申报开始日期" align="center" prop="projectAppStTime" :min-width="140" width="140">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.projectAppStTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申报结束日期" align="center" prop="projectAppEndTime" width="140">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.projectAppEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="项目预算(万)" align="center" prop="projectBudget" :min-width="180" width="180"/>
      <el-table-column label="负责人电话" align="center" prop="projectLeaderPhone" :min-width="150" width="150"/>
      <el-table-column label="操作" align="center" :min-width="280" width="280">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-top"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:application:remove']"
          >申报项目</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['scientific:application:edit']"
          >信息修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateBudget(scope.row)"
            v-hasPermi="['scientific:application:edit']"
          >预算追加</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['scientific:application: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"
    />

    <!-- 添加或修改项目申报对话框, 采用open字段控制是否 -->
    <!-- 这是提交或者详细信息的表单显示框  -->
    <!-- 这个表单的名字为form:
         在form.projectName这种方式配置参数 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" >
        <el-form-item label="项目名称" prop="projectName" >
          <el-input v-model="form.projectName" placeholder="请输入项目名称" :style="{ width: '400px' }"/>
        </el-form-item>
        <el-form-item label="项目负责人" prop="projectLeader">
          <el-input v-model="form.projectLeader" placeholder="请输入项目负责人" :style="{ width: '100px'}"/>
        </el-form-item>
        <el-form-item label="状态" prop="projectStatus" >
          <el-input v-model="form.projectStatus" placeholder="请输入状态" :style="{ width: '50px' }"/>
        </el-form-item>
        <el-form-item label="申报开始日期" prop="projectAppStTime" >
          <el-date-picker clearable
            v-model="form.projectAppStTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择申报开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申报结束日期" prop="projectAppEndTime">
          <el-date-picker clearable
            v-model="form.projectAppEndTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择申报结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目预算(万)" prop="projectBudget">
          <el-input v-model="form.projectBudget" placeholder="请输入项目预算(万)" :style="{ width: '100px'}"/>
        </el-form-item>
        <el-form-item label="项目负责人电话" prop="projectLeaderPhone">
          <el-input v-model="form.projectLeaderPhone" placeholder="请输入项目负责人联系电话" :style="{ width: '140px'}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApplication, getApplication, delApplication, addApplication, updateApplication } from "@/api/scientific/application";
import { listProcess} from "@/api/workflow/process";
export default {
  name: "Application",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目申报表格数据
      applicationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: undefined,
        projectStatus: undefined,
        projectAppProcId: undefined,
        projectAppStaus: undefined,
        projectAppStTime: undefined,
        projectAppEndTime: undefined,
        projectLeader: undefined,
        projectBudget: undefined,
        projectLeaderPhone: undefined,
      },
      queryProcParams: {
        pageNum: 1,
        pageSize: 10,
        processKey: undefined,
        processName: "项目预算追加表",
        category: "001"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "项目ID不能为空", trigger: "blur" }
        ],
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        projectStatus: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        projectAppStTime: [
          { required: true, message: "申报开始日期不能为空", trigger: "blur" }
        ],
        projectAppEndTime: [
          { required: true, message: "申报结束日期不能为空", trigger: "blur" }
        ],
        projectLeader: [
          { required: true, message: "项目负责人不能为空", trigger: "blur" }
        ],
        projectBudget: [
          { required: true, message: "项目预算(万)不能为空", trigger: "blur" }
        ],
        projectLeaderPhone: [
          { required: true, message: "项目负责人联系电话不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  // logzhan : 当我们跳转到其他路由页面，例如预算变更的时候，再次回来时
  // 需要用这个函数刷新列表，否则列表将处于刷新状态不显示信息
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.getList()
    })
  },
  methods: {
    /** 查询项目申报列表 */
    getList() {
      this.loading = true;
      listApplication(this.queryParams).then(response => {
        this.applicationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: undefined,
        projectName: undefined,
        projectStatus: undefined,
        projectAppProcId: undefined,
        projectAppStaus: undefined,
        projectAppStTime: undefined,
        projectAppEndTime: undefined,
        projectLeader: undefined,
        projectBudget: undefined,
        projectLeaderPhone: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目申报";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const projectId = row.projectId || this.ids
      getApplication(projectId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改项目申报";
        console.log(this.form)
      });
    },
    /**
     * 根据填写的项目信息进行申报 
     */
    declareProject(row){

    },
    /** 修改按钮操作 */
    handleUpdateBudget(row) {
      this.loading = true;
      this.reset();
      const upProjectId = row.projectId || this.ids

      // 查询项目经费追加流程
      listProcess(this.queryProcParams).then(response => {
        this.processParams = response.rows[0];
        this.deploymentId = this.processParams.deploymentId;
        this.definitionId = this.processParams.definitionId;
        // 流程名称暂时没有太大作用
        // this.processName = this.processParams.processName;
        this.$router.push({
          path: `/workflow/process/proj_update/${this.deploymentId}?definitionId=${this.definitionId}`,
          query: {
            projectId: upProjectId
          }
        });
      })
    },

    /** 提交按钮 */
    submitForm() {
      // $refs["form"].validate(valid => 验证表单是否有效
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          // 判断是修改还是新增
          if (this.form.projectId != null) {
            console.log(this.form)
            updateApplication(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              // 提交成功后刷新列表
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            
            addApplication(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$modal.confirm('是否确认删除项目申报编号为"' + projectIds + '"的数据项？').then(() => {
        this.loading = true;
        return delApplication(projectIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('scientific/application/export', {
        ...this.queryParams
      }, `application_${new Date().getTime()}.xlsx`)
    },
    /**
     * 把项目状态的code转换未文字: 0 : 未立项  1: 审核中  2: 已立项 
     * @param   {number|string} cellValue - 原始数值
     * @returns {string} 转换后的字符串
     * @author  zhanli
     */
    formatProjectAppStatus(cellValue) {
      switch (cellValue) {
        case '0':
          return "未立项";
        case '1':
          return "审核中";
        case '2':
          return "已立项";
        default:
          return "未知状态";
      }
    },
    /**
     * 把项目状态的申报code转换为文字: 0 : 未申报  1: 审核中  2: 已申报  
     * @param   {number|string} cellValue - 原始数值
     * @returns {string} 转换后的字符串
     * @author  zhanli
     */
    formatProjectDeclareStatus(cellValue) {
      switch (cellValue) {
        case '0':
          return "草稿";
        case '1':
          return "审核中";
        case '2':
          return "申报通过";
        default:
          return "未知状态";
      }
    },
    getTagType(status) {
      switch (status) {
        case '2':
          // 显示绿色 审核通过绿色
          return 'success';
        case '1':
          // 审核中 显示黄色
          return 'warning';
        case '0':
          // 未申报, 灰色
          return 'primary';
        case '4':
          // 其他状态 灰色
          return 'info';
        default:
          return '';
      }
    }
  }
};
</script>
