<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="card" class="custom-tab" @tab-click="handleClick">
      <el-tab-pane label="领用记录" name="first">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="领用日期" prop="collectDate">
            <el-date-picker
              clearable
              v-model="queryParams.collectDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择领用日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="选择搜索条件">
            <el-select v-model="queryParams.searchField" placeholder="请选择搜索条件" clearable>
              <el-option
                v-for="dict in dict.type.buyer_material_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 style="width: 150px" v-model="queryParams.approvaler" placeholder="请选择" clearable>
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="领料人">
            <el-select v-model="queryParams.collecter"
                       style="width: 150px" placeholder="请选择" clearable>
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userName"
              />
            </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:material:add']"
            >新增记录
            </el-button>
          </el-form-item>
        </el-form>


        <el-table stripe v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="项目名称" align="center" prop="projectName" />
          <el-table-column label="领用日期" align="center" prop="collectDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.collectDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="审批人" align="center" prop="approvaler" />
          <el-table-column label="领料人" align="center" prop="collecter" />
          <el-table-column label="物料名称" align="center" prop="name" />
          <el-table-column label="数量" align="center" prop="number" />
          <el-table-column label="单价" align="center" prop="price" />
          <el-table-column label="总金额" align="center" prop="amount" />
          <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" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.buyerFileInfos && scope.row.buyerFileInfos.length > 0"
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleDownLoad(scope.row)"
                v-hasPermi="['buyer:material:edit']"
              >下载
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['buyer:material: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-tab-pane>
      <el-tab-pane label="项目统计" name="second">
        <ProjectStatistics ref="statistics" :api="materialStatist" :columns="statisticsColumns"></ProjectStatistics>
      </el-tab-pane>
    </el-tabs>


    <!-- 添加或修改项目材料领用记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择搜索条件" clearable>
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="领用日期" prop="collectDate">
          <el-date-picker
            clearable
            v-model="form.collectDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择领用日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="领料人" prop="collecter">
          <el-select v-model="form.collecter" placeholder="请选择领料人" clearable>
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审批人" prop="approvaler">
          <el-select v-model="form.approvaler" placeholder="请选择审批人" clearable>
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物料名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="数量" prop="number">
          <el-input v-model="form.number" type="number" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" type="number" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="总金额">
          {{ form.number * form.price }}
        </el-form-item>
        <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 { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial, materialStatist } from '@/api/buyer/material'
import { listProject } from '@/api/buyer/project'
import { listUser } from '@/api/system/user'
import ProjectStatistics from "@/views/buyer/components/project-statistics"
import { fileDownload } from "@/utils"

export default {
  name: 'Material',
  components: { ProjectStatistics },
  dicts: ['buyer_material_search_fields'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目材料领用记录表格数据
      materialList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        remarks: null,
        projectId: null,
        collectDate: null,
        collecter: null,
        approvaler: null,
        name: null,
        number: null,
        price: null,
        amount: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: '请选择项目', trigger: 'blur' }
        ],
        collectDate: [
          { required: true, message: '请选择领用日期', trigger: 'blur' }
        ],
        collecter: [
          { required: true, message: '请选择领料人', trigger: 'blur' }
        ],
        approvaler: [
          { required: true, message: '请选择审批人', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请填写物料名称', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '数量不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '单价不能为空', trigger: 'blur' }
        ]
      },
      projectList: [],
      userList: [],
      activeName: 'first',
      statisticsColumns: [
        { label: '项目名称', prop: 'projectName' },
        { label: '累积领取物料次数', prop: 'totalTimes' },
        { label: '累积领取物料数量', prop: 'totalNumber' },
        { label: '累积领用物料金额', prop: 'totalAmount' }
      ],
      materialStatist: materialStatist
    }
  },
  created() {
    this.getList()
    listProject({ pageNum: 1, pageSize: 99999 }).then(res => {
      this.projectList = res.rows
    })
    listUser({ pageNum: 1, pageSize: 99999 }).then(res => {
      this.userList = res.rows
    })
  },
  methods: {
    handleClick(){
      if(this.activeName == 'second'){
        this.$refs.statistics.getList()
      }
    },
    /** 查询项目材料领用记录列表 */
    getList() {
      this.loading = true
      listMaterial(this.addSearchField(this.queryParams, this.queryParams.searchField, this.queryParams.keyword)).then(response => {
        this.materialList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remarks: null,
        delFlag: null,
        projectId: null,
        collectDate: null,
        collecter: null,
        approvaler: null,
        name: null,
        number: null,
        price: null,
        amount: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams= {
        pageNum: 1,
        pageSize: 10,
      }
      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
      getMaterial(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改项目材料领用记录'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.amount = this.form.price * this.form.number
          if (this.form.id != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addMaterial(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 delMaterial(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleDownLoad(row) {
      const filePathArray = row.buyerFileInfos.map(item => item.fileUrl)
      fileDownload({ filePathArray: filePathArray.join(',') })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('buyer/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped lang="scss">
.app-container {
  .custom-tab {
    .el-tabs__content {
      overflow: inherit !important;
    }
  }
}
</style>
