<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="采购申请部门" prop="purchaseDeptId">-->
<!--        <el-input-->
<!--          v-model="queryParams.purchaseDeptId"-->
<!--          placeholder="请输入采购申请部门"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <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="specifications">-->
<!--        <el-input-->
<!--          v-model="queryParams.specifications"-->
<!--          placeholder="请输入规格"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="型号" prop="modelType">-->
<!--        <el-select v-model="queryParams.modelType" placeholder="请选择型号" clearable size="small">-->
<!--          <el-option label="请选择字典生成" value="" />-->
<!--        </el-select>-->
<!--      </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 type="selection" width="55" align="center" />-->
<!--      <el-table-column label="采购主键" align="center" prop="purchaseId" />-->
<!--      <el-table-column label="采购申请部门" align="center" prop="purchaseDeptName" />-->
      <el-table-column label="采购名称" align="center" prop="purchaseName" :show-overflow-tooltip="true" width="150"/>
<!--      <el-table-column label="规格" align="center" prop="specifications" />-->
<!--      <el-table-column label="型号" align="center" prop="modelType" />-->
      <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="price" />
      <el-table-column label="数量" align="center" prop="count" />
      <el-table-column label="总价" align="center" prop="total" />
      <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="remark" />-->
      <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="180">
        <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="purchaseDeptId">-->
<!--              <el-input v-model="form.purchaseDeptId" placeholder="请输入采购申请部门" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="采购名称" prop="purchaseName">
              <el-input v-model="form.purchaseName" placeholder="请输入采购名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格" prop="specifications">
              <el-input v-model="form.specifications" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="modelType">
              <el-input v-model="form.modelType" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="用途说明" prop="applicationDescription">
              <el-input v-model="form.applicationDescription" placeholder="请输入用途说明" />
            </el-form-item>
          </el-col>

        </el-row>

        <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-col :span="12">
            <el-form-item label="单价" prop="price" >
              <el-input v-model="form.price" placeholder="请输入单价" @blur="sumAmount"/>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="数量" prop="count">
              <el-input v-model="form.count" placeholder="请输入数量" @blur="sumAmount"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总价" prop="total">
              <el-input v-model="form.total" placeholder="请输入总价" :disabled=true />
            </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" 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,
        purchaseName: null,
        specifications: null,
        modelType: null,
        applicationDescription: null,
        userId: null,
        price: null,
        count: null,
        total: null,
        purchaseDeptManagerId: null,
        approvedUserId: null,
        isDel: null,
        purchaseStatus: null,
        approvedTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        purchaseName: [
          { required: true, message: "采购名称不能为空", trigger: "blur" },
        ],
        specifications: [
          { required: true, message: "规格不能为空", trigger: "blur" },
        ],
        modelType: [
          { required: true, message: "型号不能为空", trigger: "blur" },
        ],
        applicationDescription: [
          { required: true, message: "用途不能为空", trigger: "blur" },
        ],
        userId: [
          { required: true, message: "请选择使用人", trigger: "change" },
        ],
        price: [
          { required: true, message: "单价不能为空", trigger: "blur" },
        ],
        count: [
          { required: true, message: "数量不能为空", trigger: "blur" },
        ],
        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
      );
    },
    //计算总价
    sumAmount() {
      if (this.form.price && this.form.count) {
        this.form.total = this.accMul(
          this.form.price,
          this.form.count
        );
      } else {
        this.form.total = "";
      }
    },
    //浮点计算出现无限小数
    accMul(arg1, arg2) {
      var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
      try {
        m += s1.split(".")[1].length;
      } catch (e) {}
      try {
        m += s2.split(".")[1].length;
      } catch (e) {}
      return (
        (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
        Math.pow(10, m)
      );
    },
    /** 查询外部采购（报销）申请列表 */
    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,
        specifications: null,
        modelType: null,
        applicationDescription: null,
        userId: null,
        price: null,
        count: 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 = "添加外部采购（报销）申请";
    },
    /** 修改按钮操作 */
    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>
