<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="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入采购编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请组织" prop="apply">
        <el-input
          v-model="queryParams.apply"
          placeholder="请输入申请组织"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="currency">
        <el-date-picker clearable
          v-model="queryParams.currency"
          type="date"
                        style="width: 205px;"
          value-format="yyyy-MM-dd"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="申请部门" prop="department">
        <el-input
          v-model="queryParams.department"
          placeholder="请输入申请部门"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="申请人" prop="applypeople">
        <el-input
          v-model="queryParams.applypeople"
          placeholder="请输入申请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批人" prop="approval">
        <el-input
          v-model="queryParams.approval"
          placeholder="请输入审批人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批时间" prop="approvaltime">
        <el-date-picker clearable
          v-model="queryParams.approvaltime"
          type="date"
          style="width: 205px;"
          value-format="yyyy-MM-dd"
          placeholder="请选择审批时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-input
          v-model="queryParams.state"
          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="['amichi:purchaseOrder: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="['amichi:purchaseOrder: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="['amichi:purchaseOrder: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="['amichi:purchaseOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" style="margin-top: 20px"  :data="purchaseOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="采购编号" align="center" prop="number" />
      <el-table-column label="申请组织" align="center" prop="apply" />
      <el-table-column label="申请时间" align="center" prop="currency"/>
      <el-table-column label="申请部门" align="center" prop="department" />
      <el-table-column label="合计金额" align="center" prop="total" />
      <el-table-column label="申请人" align="center" prop="applypeople" />
      <el-table-column label="创建人" align="center" prop="createpeople" />

<!--      <el-table-column label="备用" align="center" prop="sparea" />-->
      <el-table-column label="状态" align="center" prop="state" >
        <template  v-slot="scope">
          <el-tag :type="getStatusType(scope.row.state)" disable-transitions> <dict-tag  :options="dict.type.cgspzt" :value="scope.row.state"/></el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approval" />
      <el-table-column label="审批时间" align="center" prop="approvaltime"/>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown @command="(command)=>{handleCommand(command, scope.row)}">
            <el-button type="warning">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item  icon="el-icon-edit"  command="handleUpdate">修改</el-dropdown-item>
              <el-dropdown-item  icon="el-icon-delete" command="handleDelete">删除</el-dropdown-item>
              <el-dropdown-item  icon="el-icon-delete" command="initiateApproval">发起审批</el-dropdown-item>
              <el-dropdown-item  icon="el-icon-delete" command="catDetails">查看详情</el-dropdown-item>

            </el-dropdown-menu>
          </el-dropdown>
        </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="查看详情" :visible.sync="catOpen" width="1000px" append-to-body>
        <el-row type="flex" class="row-bg" justify="space-between">
          <el-col :span="6"><div class="bt">单据编号</div></el-col>
          <el-col :span="6"><div class="bt">申请组织</div></el-col>
          <el-col :span="6"><div class="bt" style="padding-left: 27px">币别</div></el-col>
        </el-row>
        <el-row type="flex" class="row-bg" justify="space-between">
          <el-col :span="6"><div class="bt">申请日期</div></el-col>
          <el-col :span="6"><div class="bt">申请部门</div></el-col>
          <el-col :span="6"><div class="bt">合计金额</div></el-col>
        </el-row>
    </el-dialog>
    <!-- 添加或修改采购对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row type="flex" class="row-bg" justify="space-between">
          <el-col :span="8">
            <el-form-item label="采购编号" prop="number">
              <el-input v-model="form.number" placeholder="请输入采购编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请组织" prop="apply">
              <el-input v-model="form.apply" placeholder="请输入申请组织" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请时间" prop="applytime">
              <el-date-picker clearable
                              v-model="form.applytime"
                              type="date"
                              style="width: 306.32px"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择申请时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg" justify="space-between">
          <el-col :span="8">
            <el-form-item label="申请部门" prop="department">
              <el-input v-model="form.department" placeholder="请输入申请部门" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="币别" prop="currency">
              <el-input v-model="form.currency" placeholder="请输入申请组织" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合计金额" prop="total">
              <el-input v-model="form.total" placeholder="请输入合计金额" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="8">
            <el-form-item label="申请人" prop="applypeople">
              <el-input v-model="form.applypeople" placeholder="请输入申请人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
<!--            type="textarea"-->
            <el-form-item label="备注" prop="applypeople">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="">
          <div class="cesiumTabRoot">
            <el-table
              :data="detailData"
              border
              show-summary
              :summary-method="getSummaries"
              :cell-class-name="tabCellClassName"
              :row-class-name="tabRowClassName"
              @cell-click="cellClick"
              style="width:100%">
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="50">
              </el-table-column>
              <el-table-column
                prop="organization"
                align="center"
                label="采购组织"
              >
                <template v-slot="{ row, column }">
                    <el-input
                      v-if="rowIndex === row.index && columnIndex === column.index"
                      v-model="row.organization"
                      @blur="hideInput(detailData,row.index,columnIndex,'organization')"
                    >
                    </el-input>
                    <!-- 显示 -->
                    <span v-else>{{ row.organization }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="demand"
                label="需求组织"
                align="center"
              >
                <template v-slot="{ row, column }">
                  <el-input
                    v-if="rowIndex === row.index && columnIndex === column.index"
                    v-model="row.demand"
                    @blur="hideInput"></el-input>
                  <!-- 显示 -->
                  <span v-else>{{ row.demand }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="materialnum"
                label="物料编码"
                align="center"
              >
                <template v-slot="{ row, column }">
                  <!-- 编辑 -->
                  <el-input
                    v-if="rowIndex === row.index && columnIndex === column.index"
                    v-model="row.materialnum"
                    @blur="hideInput"></el-input>
                  <!-- 显示 -->
                  <span v-else>{{ row.materialnum }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="materialname"
                align="center"
                :label="'物料名称'">
                <template v-slot="{ row, column }">
                  <!-- 编辑 -->
                  <el-input
                    v-if="rowIndex === row.index && columnIndex === column.index"
                    v-model="row.materialname"
                    @blur="hideInput"></el-input>
                  <!-- 显示 -->
                  <span v-else>{{ row.materialname }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="model"
                label="规格型号"
                align="center"
              >
                <template v-slot="{ row, column }">
                  <!-- 编辑 -->
                  <el-input

                    v-if="rowIndex === row.index && columnIndex === column.index"
                    v-model="row.model"
                    @blur="hideInput"></el-input>
                  <!-- 显示 -->
                  <span v-else>{{ row.model }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="company"
                label="单位"
                align="center"
              >
                <template v-slot="{ row, column }">
                  <!-- 编辑 -->
                  <el-input

                    v-if="rowIndex === row.index && columnIndex === column.index"
                    v-model="row.company"
                    @blur="hideInput"></el-input>
                  <!-- 显示 -->
                  <span v-else>{{ row.company }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="quantity"
                label="申请数量"
                align="center"
                sortable
              >
                <template v-slot="{ row, column }">
                  <!-- 编辑 -->
                  <el-input
                    v-if="rowIndex === row.index && columnIndex === column.index"
                    v-model="row.quantity"
                    @blur="hideInput('sl')"></el-input>
                  <!-- 显示 -->
                  <span v-else>{{ row.quantity }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="approval"
                label="批准数量"
                align="center"
                sortable
              >
                <template v-slot="{ row, column }">
                  <!-- 编辑 -->
                  <el-input
                    v-if="rowIndex === row.index && columnIndex === column.index"
                    v-model="row.approval"
                    @blur="hideInput('sl')"></el-input>

                  <!-- 显示 -->
                  <span v-else>{{ row.approval }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="remark"
                label="到货日期"
                align="center"
                width="180"
              >
                <template v-slot="{ row, column }">
                  <!-- 编辑 -->
                  <el-date-picker
                    style="width: 100%"
                    v-if="rowIndex === row.index && columnIndex === column.index"
                    v-model="row.reachtime"
                    prop
                    type="date"
                    @blur="hideInput"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                  </el-date-picker>
                  <!-- 显示 -->
                  <span v-else>{{ row.reachtime }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="remark"
                label="备注"
                align="center"
              >
                <template v-slot="{ row, column }">
                  <!-- 编辑 -->
                  <el-input
                    v-if="rowIndex === row.index && columnIndex === column.index"
                    v-model="row.remark"
                    prop
                    @blur="hideInput"></el-input>
                  <!-- 显示 -->
                  <span v-else>{{ row.remark }}</span>
                </template>
              </el-table-column>

              <el-table-column
                align="center"
                fixed="right"
                label="操作"
                width="120">
                <template v-slot="scope">
                  <el-button type="danger"  size="small" icon="el-icon-delete" @click.native.prevent="deleteRow(scope.$index, detailData)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-row>
        <el-row type="flex" class="row-bg" justify="space-between" style="margin-top: 20px">
          <el-col  :span="10">
          </el-col>
          <el-col  :span="10">
            <el-button type="primary" style="float: right" icon="el-icon-circle-plus" @click="addDetails">新增明细</el-button>
          </el-col>
        </el-row>
<!--        <el-row type="flex" class="row-bg" justify="space-between" style="margin-top: 20px">-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="创建人" prop="createpeople">-->
<!--              <el-input v-model="form.createpeople" placeholder="请输入创建人" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="审批人" prop="approval">-->
<!--              <el-input v-model="form.approval" placeholder="请输入审批人" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->

<!--        <el-form-item label="审批时间" prop="approvaltime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.approvaltime"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="审批时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="审批时间" prop="createTime">-->
<!--          <el-date-picker clearable-->
<!--                          v-model="form.createTime"-->
<!--                          type="date"-->
<!--                          value-format="yyyy-MM-dd"-->
<!--                          placeholder="创建时间">-->
<!--          </el-date-picker>-->
<!--        </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 {
  listPurchaseOrder,
  addPurchaseOrderVo,
  getPurchaseOrderOne,
  getPurchaseOrder,
  updatePurchaseOrderVo,
  delPurchaseOrder,
  addPurchaseOrder,
  updatePurchaseOrder,
  updatePurchaseOrderState
} from "@/api/amichi/purchase/purchaseOrder";

export default {
  name: "PurchaseOrder",
  dicts: ["cgspzt"],
  data() {
    return {
      catOpen:false,
      // 行index
      rowIndex: null,
      // 列index
      columnIndex: null,
      detailData:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购表格数据
      purchaseOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        number: null,
        apply: null,
        currency: null,
        department: null,
        total: null,
        applypeople: null,
        createpeople: null,
        approval: null,
        approvaltime: null,
        sparea: null,
        state: null,
        createById: null,
        updateById: null,
        dataApprovalStatus: null,
        processKey: null,
        taskProcessKey: null,
        taskNodeKey: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //展示不同的标签
    getStatusType(status) {
      switch (status) {
        case '3':
          return 'warning';
        case '0':
          return 'danger';
        case '1':
          return 'success';
        case '2':
          return 'info';
        default:
          return '';
      }
    },
    //下拉菜单点击事件
    handleCommand(command, row) {
      switch (command) {
        case "handleUpdate":
          this.handleUpdate(row)
          break;
        case "handleDelete":
          this.handleDelete(row)
          break;
        case "initiateApproval":
          this.initiateApproval(row)
          break;
        case "catDetails":
          this.catDetails(row)
          break;

        default:
          break;
      }
    },
    //查看详情
    catDetails(row){
      this.catOpen=true;
    },
    initiateApproval(row){
      //发起审批改状态
      let data={"id":row.id,state:0}
      updatePurchaseOrderState(data).then((res)=>{
        this.$modal.msgSuccess("发起审批成功");
        this.getList();
      });
    },
    // 对列进行合算
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        // 只对amount这一列进行总计核算。
        if (column.property === 'quantity') {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              }else {
                return prev;
              }
            }, 0);
            // sums[index] += ' 元';
          } else {
            // sums[index] = '---'
          }
        }
        if (column.property === 'approval') {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              }else {
                return prev;
              }
            }, 0);
            // sums[index] += ' 元';
          } else {
            // sums[index] = '---'
          }
        }
      });
      return sums;
    },
    //新增明细
    addDetails(){
      this.detailData.push(
        {"organization":"","demand":"","materialnum":"","materialname":"","model":"","company":"","quantity":0,"approval":0,"reachtime":"","remark":""});
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    // 表格input失去焦点
    hideInput(a,b,c,d) {
      if(a=="sl"){
        this.updateTotalQuantity();
      }
      // console.log(a,b,c,d)
      // console.log(a[b-1])
      // console.log("33333")
      // if(a[b-1]){
      //   console.log("a")
      //   if(a[b-1][`${d}`]!=undefined&&a[b-1][`${d}`]!=""){
      //     a[b-1].isEmpty[`${d}`]=false;
      //     console.log("h")
      //   }else {
      //     console.log("m")
      //     a[b-1].isEmpty[`${d}`]=true;
      //   }
      // }
      // console.log(this.detailData)
      this.rowIndex = null;
      this.columnIndex = null;
    },
    // 点击表格单元格编辑
    cellClick(row, column) {
      this.rowIndex = row.index;
      this.columnIndex = column.index;
    },
    // 给表格单元格数据添加列下标
    tabCellClassName({ column, columnIndex }) {
      column.index = columnIndex + 1;
    },
    // 表格行class-name
    tabRowClassName({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 查询采购列表 */
    getList() {
      this.loading = true;
      listPurchaseOrder(this.queryParams).then(response => {
        this.purchaseOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        number: null,
        apply: null,
        currency: null,
        department: null,
        total: null,
        applypeople: null,
        createpeople: null,
        approval: null,
        approvaltime: null,
        sparea: null,
        state: null,
        remark: null,
        createById: null,
        createBy: null,
        createTime: null,
        updateById: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        dataApprovalStatus: null,
        processKey: null,
        taskProcessKey: null,
        taskNodeKey: 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.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.detailData=[];
      this.open = true;
      this.title = "添加采购";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.detailData=[];
      const id = row.id || this.ids
      getPurchaseOrderOne(id).then(response => {
        this.form = response.data;
        this.detailData = response.data.pocurementdetailsList;
        this.open = true;
        this.title = "修改采购";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.pocurementdetailsList = this.detailData;
            updatePurchaseOrderVo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.pocurementdetailsList = this.detailData;
            addPurchaseOrderVo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购编号为"' + ids + '"的数据项？').then(function() {
        return delPurchaseOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('amichi/purchaseOrder/export', {
        ...this.queryParams
      }, `purchaseOrder_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.bt{
  text-align: left;
  border: 1px solid red;
}
</style>
