<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="选择搜索条件">
        <el-select v-model="queryParams.searchField" placeholder="请选择搜索条件" clearable>
          <el-option
            v-for="dict in dict.type.buyer_project_search_fields"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键词搜索"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目状态">
        <el-select v-model="queryParams.status" placeholder="请选择项目状态" clearable>
          <el-option
            v-for="dict in dict.type.buyer_project_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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-button
          type="primary"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['buyer:project:add']"
        >新增项目
        </el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['buyer:project: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="['buyer:project: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="['buyer:project:export']"-->
<!--        >导出-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->

    <el-table stripe v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目名称" align="center" prop="name" />
      <el-table-column label="项目预算（万元）" align="center" prop="budget" />
      <el-table-column label="项目时间" align="center" prop="createTime" />
      <el-table-column label="开始时间" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目负责人" align="center" prop="employeeName" />
      <el-table-column label="项目组成员" align="center" prop="buyerProjectMemberArray">
        <template slot-scope="scope">
          {{ scope.row.buyerProjectMemberArray ? scope.row.buyerProjectMemberArray.length : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="其他附件" align="center" prop="buyerFileInfos">
        <template slot-scope="scope">
          {{ scope.row.buyerFileInfos.length }}
        </template>
      </el-table-column>
      <el-table-column label="项目状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.buyer_project_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="最后操作人" align="center" prop="updateBy" />
      <el-table-column label="最后操作时间" align="center" prop="updateTime" />
      <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="['buyer:project:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['buyer:project: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="600px" append-to-body fullscreen>
      <el-form ref="form" :model="form" :rules="rules" inline class="modal-inline-form" label-width="170px">
        <template>
          <div class="tab-title">项目信息</div>
          <el-divider></el-divider>
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="预算金额" prop="budget">
            <el-input v-model="form.budget" placeholder="请输入预算金额" />
          </el-form-item>
          <el-form-item label="来源" prop="resource">
            <el-select v-model="form.resource" placeholder="请选择来源" clearable>
              <el-option
                v-for="dict in dict.type.buyer_project_resource"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="承担单位" prop="assumeCompany">
            <el-input v-model="form.assumeCompany" placeholder="请输入承担单位" />
          </el-form-item>
          <el-form-item label="开展形式" prop="expandedForm">
            <el-select v-model="form.expandedForm" placeholder="请选择开展形式" clearable>
              <el-option
                v-for="dict in dict.type.buyer_project_expanded_form"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              clearable
              v-model="form.startDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择开始日期"
              @change="getProjectActiveEmployee"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              clearable
              v-model="form.endDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择结束日期"
              @change="getProjectActiveEmployee"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item></el-form-item>
        </template>
        <template>
          <div class="tab-title">项目负责人情况</div>
          <el-divider></el-divider>
          <el-form-item label="项目负责人姓名" prop="employeeId">
            <el-select v-model="form.employeeId" placeholder="请选择项目负责人" clearable @change="handleEmployeeNameChange">
              <el-option
                v-for="user in employeeList"
                :key="user.id"
                :label="user.name"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <dict-tag :options="dict.type.sys_user_sex" :value="form.sex" :disabled="true"/>
          </el-form-item>
          <el-form-item label="学历" prop="education">
            <el-input v-model="form.education" :disabled="true" />
          </el-form-item>
          <el-form-item label="出生日期" prop="birthdate">
            <el-input v-model="form.birthdate" :disabled="true" />
          </el-form-item>
          <el-form-item label="部门" prop="dept">
            <el-input v-model="form.dept" :disabled="true" />
          </el-form-item>
          <el-form-item label="职务" prop="post">
            <el-input v-model="form.post" :disabled="true" />
          </el-form-item>
        </template>
        <template>
          <div class="tab-title">项目组成员</div>
          <el-divider></el-divider>
          <el-form-item label="项目组成员" prop="buyerProjectMemberArray">
            <el-select
              multiple
              clearable
              remote
              filterable
              :remote-method="remoteMethod"
              :loading="selectLoading"
              v-model="form.buyerProjectMemberArray"
              placeholder="请选择项目组成员"
            >
              <el-option
                v-for="employee in employeeList"
                :key="employee.id"
                :label="employee.name"
                :value="employee.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="已选择成员" prop="deptId">
            <el-tag v-for="item in form.buyerProjectMemberArray" :key="item">{{ getName(item) }}</el-tag>
          </el-form-item>
        </template>

        <template>
          <div class="tab-title">项目描述</div>
          <el-divider></el-divider>
          <el-form-item label="立项背景" prop="projectInfo">
            <el-input v-model="form.projectInfo" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="项目进度" prop="projectProgress">
            <el-input v-model="form.projectProgress" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="关键技术" prop="keyTechnology">
            <el-input v-model="form.keyTechnology" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="创新性" prop="innovation">
            <el-input v-model="form.innovation" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="预期成果目标" prop="expecteResult">
            <el-input v-model="form.expecteResult" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item></el-form-item>
        </template>

        <div class="tab-title">其他</div>
        <el-divider></el-divider>
        <el-form-item label="上传立项决议或其他附件" prop="buyerFileInfos">
          <FileUploadMultiple v-model:value="form.buyerFileInfos" :limit="10" :file-size="10" :drag="true" :fileType="null"></FileUploadMultiple>
        </el-form-item>
      </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 { listProject, getProject, delProject, addProject, updateProject, getProjectEmployee } from '@/api/buyer/project'
import { listEmployee } from '@/api/buyer/employee'
import { getDicts } from '@/api/system/dict/data'

export default {
  name: 'Project',
  dicts: [
    'buyer_project_search_fields',
    'buyer_project_status',
    'buyer_project_resource',
    'buyer_project_expanded_form',
    'sys_user_sex'
  ],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 立项管理表格数据
      projectList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchField: null,
        keyword: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '请填写项目名称', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择开始时间', trigger: 'blur' }
        ],
        endDate: [
          { required: true, message: '请选择结束时间', trigger: 'blur' }
        ],
        employeeId: [
          { required: true, message: '请选择负责人姓名', trigger: 'blur' }
        ]
      },
      userList: [],
      employeeList: [],
      selectLoading: false
    }
  },
  created() {
    this.getList()
    // listEmployee({ pageNum: 1, pageSize: 99999 }).then(response => {
    //   this.userList = response.rows
    // })
    this.getProjectActiveEmployee()
  },
  methods: {
    getProjectActiveEmployee() {
      getProjectEmployee({ startDate: this.form.startDate, endDate: this.form.endDate }).then(res => {
        this.employeeList = res.data
      })
    },
    handleEmployeeNameChange() {
      const matchUser = this.employeeList.find(item => item.id === this.form.employeeId)
      const { sex, education, birthdate, dept, post } = matchUser
      this.form.sex = sex
      this.form.education = education
      this.form.birthdate = birthdate
      this.form.dept = dept
      this.form.post = post
    },
    remoteMethod(query) {
      this.selectLoading = true
      getProjectEmployee({ name: query }).then(res => {
        this.employeeList = res.data
        this.selectLoading = false
      })
    },
    /** 查询立项管理列表 */
    getList() {
      this.loading = true
      listProject(this.addSearchField(this.queryParams, this.queryParams.searchField, this.queryParams.keyword)).then(response => {
        this.projectList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams= {
        pageNum: 1,
          pageSize: 10,
          searchField: null,
          keyword: null,
          status: null
      }
      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
      getProject(id).then(response => {
        this.form = response.data
        this.getProjectActiveEmployee()
        this.open = true
        this.title = '修改立项管理'
      })
    },
    /** 提交按钮 */
    submitForm() {
      // 判断时间
      if(this.form.endDate < this.form.startDate){
        this.$modal.msgError('结束时间不能小于开始时间！')
        return
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除立项管理选中的数据项？').then(function() {
        return delProject(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`)
    },
    getName(id) {
      return this.employeeList.find(item => item.id === id).name
    }
  }
}
</script>

<style scoped lang="scss">
.modal-inline-form {
  display: flex;
  flex-wrap: wrap;

  .el-form-item {
    width: calc(50% - 20px);
  }
}
</style>
