<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="费用名称" prop="purchaseName">
        <el-input
          v-model="queryParams.purchaseName"
          placeholder="请输入费用名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用途" prop="applicationDescription">
        <el-input
          v-model="queryParams.applicationDescription"
          placeholder="请输入用途"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报销人" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入报销人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="采购状态" prop="purchaseStatus">
        <el-select v-model="queryParams.purchaseStatus" placeholder="请选择采购状态" clearable size="small">
          <el-option
            v-for="item in purchaseStatusList"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </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-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="['system:purchase: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="['system:purchase: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="['system:purchase:remove']"
        >删除</el-button>
      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--		  :loading="exportLoading"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['system:purchase:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseList">
      <el-table-column label="费用名称" align="center" prop="purchaseName" :show-overflow-tooltip="true" width="150"/>
      <el-table-column label="金额" align="center" prop="total" />
      <el-table-column label="用途" align="center" prop="applicationDescription" :show-overflow-tooltip="true"/>
      <el-table-column label="报销人" align="center" prop="userName" />
      <el-table-column label="申请时间" align="center" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approvedUserName">
        <template slot-scope="scope">
          <span v-if="scope.row.approvedUserName == null">-</span>
          <span v-else>{{scope.row.approvedUserName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="purchaseStatus" :formatter="getPurchaseStatus" width="120"/>
      <el-table-column label="审核时间" align="center" prop="approvedTime" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.approvedUserName == null">-</span>
          <span v-else>{{ parseTime(scope.row.approvedTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['system:purchase:edit']"-->
<!--          >修改</el-button>-->
          <OperatorButton
            operatorName="purchaseDetail"
            :purchaseInfo="scope.row"
            @getList="getList"
          />

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:purchase:remove']"
            v-if="(scope.row.purchaseStatus == '0' || scope.row.purchaseStatus == '3') && scope.row.handledByUserId == $store.state.user.userId"
          >删除</el-button>
          <OperatorButton
            v-for="item in scope.row.operators"
            :key="item"
            :operatorName="item"
            :purchaseInfo="scope.row"
            @getList="getList"
          />
        </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="800px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="费用名称" prop="purchaseName">
              <el-input v-model="form.purchaseName" placeholder="请输入费用名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="total">
              <el-input v-model="form.total" type="number" placeholder="请输入金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="用途" prop="applicationDescription">
          <el-input v-model="form.applicationDescription" placeholder="请输入用途" />
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="报销人" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择报销人" style="width: 100%">
                <el-option v-for="item in usersList"
                           :key="item.userId"
                           :label="item.nickName"
                           :value="item.userId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          style="width: 150px; border-color: #1890ff; color: #1890ff"
          @click="reset"
        >内容重置</el-button>
        <el-button type="primary" style="width: 150px" @click="submitForm"
        >提交申请</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchase, getPurchase, delPurchase, addPurchase, updatePurchase, exportPurchase } from "@/api/transaction/purchase";
import { selectTransactorByDeptId } from "@/api/system/user";
import OperatorButton from "./components/OperatorButton";
import { sendNotice } from "@/api/system/notice";
export default {
  name: "Purchase",
  components: {
    OperatorButton
  },
  data() {
    return {
      usersList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 外部采购（报销）申请表格数据
      purchaseList: [],
      purchaseStatusList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaseDeptId: null,
        purchaseType: '1',
        purchaseName: null,
        applicationDescription: null,
        userId: null,
        total: null,
        purchaseDeptManagerId: null,
        approvedUserId: null,
        isDel: null,
        purchaseStatus: null,
        approvedTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        purchaseName: [
          { required: true, message: "费用名称不能为空", trigger: "blur" },
        ],
        applicationDescription: [
          { required: true, message: "用途不能为空", trigger: "blur" },
        ],
        userId: [
          { required: true, message: "请选择使用人", trigger: "change" },
        ],
        total: [
          { required: true, message: "金额不能为空", trigger: "blur" },
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getUsers();
    this.getPurchaseStatusList();
  },
  methods: {
    getPurchaseStatusList(){

      this.getDicts("purchaseStatus").then((response) => {
        this.purchaseStatusList = response.data;
      });
    },
    //获取交易状态
    getPurchaseStatus(row) {
      return this.selectDictLabel(
        this.purchaseStatusList,
        row.purchaseStatus
      );
    },
    /** 查询外部采购（报销）申请列表 */
    getList() {
      this.loading = true;
      listPurchase(this.queryParams).then(response => {
        this.purchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseId: null,
        purchaseDeptId: null,
        purchaseName: null,
        applicationDescription: null,
        userId: null,
        total: null,
        purchaseDeptManagerId: null,
        approvedUserId: null,
        remark: null,
        createTime: null,
        isDel: null,
        updateTime: null,
        purchaseStatus: "0",
        approvedTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加服务费用申请";
      this.form.purchaseType = "1";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const purchaseId = row.purchaseId || this.ids
      getPurchase(purchaseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改服务费用申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.purchaseId != null) {
            updatePurchase(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchase(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.noticeNext();
            });
          }
        }
      });
    },
    //通知下一个人
    noticeNext(){
      sendNotice({noticeTitle:"您有新服务费用信息待确认",noticeType:"1",noticeContent:"您有新服务费用信息待确认",
        deptId:this.$store.state.user.deptId,roles:"deptLeader"})
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseIds = row.purchaseId || this.ids;
      this.$confirm('是否确认删除服务费用申请名称为"' + row.purchaseName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPurchase(purchaseIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有服务费用申请数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportPurchase(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    getUsers() {
      this.form.userId = null;
        selectTransactorByDeptId({ deptId: this.$store.state.user.deptId }).then(
          (res) => {
            this.usersList = res.data;
          }
        );
    }
  }
};
</script>
