<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="customerId">
        <el-select
          v-model="queryParams.customerId"
          placeholder="请选择客户"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option
            v-for="item in customSelectData"
            :key="item.id"
            :label="item.customName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="回单日期" prop="returnReceiptDate">
        <el-date-picker
          clearable
          v-model="queryParams.returnReceiptDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择回单日期"
        >
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="日期范围" prop="startTime">
        <el-date-picker
          v-model="timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="timeRangeChange"
        >
        </el-date-picker>
      </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:SaleAccountsReceivableDetail: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:SaleAccountsReceivableDetail: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:SaleAccountsReceivableDetail:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- :disabled="multiple" -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-claim"
          size="mini"
          @click="handlerReceipt"
          >回单</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:SaleAccountsReceivableDetail:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="SaleAccountsReceivableDetailList"
      @selection-change="handleSelectionChange"
      @cell-click="cellClick"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账务类型" align="center" prop="accountingType">
        <template slot-scope="scope">
          {{ getDictLabel(scope.row.accountingType, "accounting_type") }}
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="customName" />
      <el-table-column
        label="日期"
        align="center"
        prop="accountsReceivableDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.accountsReceivableDate, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售单号" align="center" prop="saleNo" />
      <!-- <el-table-column label="产品编号" align="center" prop="productId" /> -->
      <el-table-column label="品名" align="center" prop="productName" />
      <el-table-column
        label="规格"
        align="center"
        prop="productSpecifications"
      />
      <el-table-column label="等级" align="center" prop="productLevel" />
      <el-table-column label="颜色" align="center" prop="productColour" />
      <el-table-column label="批号" align="center" prop="lotNumber" />
      <el-table-column label="箱数" align="center" prop="boxNum" />
      <el-table-column label="重量" align="center" prop="weight" />
      <el-table-column label="单价" align="center" prop="productPrice" />
      <el-table-column label="应收" align="center" prop="amountReceivable" />
      <el-table-column label="已收" align="center" prop="receivedAmount" />
      <el-table-column label="余额" align="center" prop="amounts" />
      <el-table-column label="开票类型" align="center" prop="billingType">
        <template slot-scope="scope">
          {{
            getDictLabel(
              scope.row.billingType,
              "accounts_receivable_billing_type"
            )
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="accountsReceivableRemark"
      />
      <el-table-column label="结算单位" align="center" prop="settlementUnit" />
      <el-table-column label="回单" align="center" prop="returnReceipt">
        <template slot-scope="scope">
          <el-checkbox
            true-label="1"
            false-label="0"
            v-model="scope.row.returnReceipt"
            @change="returnReceiptChange(scope.row)"
          ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column
        label="回单日期"
        align="center"
        prop="returnReceiptDate"
        width="180"
      >
        <template slot-scope="scope">
          <el-date-picker
            style="width: 150px"
            v-if="scope.row.returnReceiptDateShow"
            v-model="scope.row.returnReceiptDate"
            type="date"
            size="mini"
            placeholder="选择日期"
            @change="returnReceiptChange(scope.row)"
          >
          </el-date-picker>

          <span v-else>{{
            parseTime(scope.row.returnReceiptDate, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="回单备注"
        align="center"
        width="100px"
        prop="returnReceiptRemark"
      >
        <template slot-scope="scope">
          <el-input
            style="width: 85px"
            v-if="scope.row.returnReceiptRemarkShow"
            v-model="scope.row.returnReceiptRemark"
            @blur="returnReceiptChange(scope.row)"
            size="mini"
          ></el-input>
          <span v-else>
            {{ scope.row.returnReceiptRemark }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="通知单号" align="center" prop="noticeNumber" />
      <!-- <el-table-column label="状态" align="center" prop="status" /> -->
      <!-- <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>
            <el-button type="warning" plain size="small">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                ><el-button
                  size="mini"
                  type="text"
                  @click="handlerReceipt(scope.row.id)"
                  >回 单</el-button
                ></el-dropdown-item
              >
              <!-- <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  @click="passHandler(scope.row)"
                  >通过</el-button
                >
              </el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:SaleAccountsReceivableDetail:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:SaleAccountsReceivableDetail: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户编号" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入客户编号" />
        </el-form-item>
        <el-form-item label="应收账日期" prop="accountsReceivableDate">
          <el-date-picker
            clearable
            v-model="form.accountsReceivableDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择应收账日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="销售单号" prop="saleNo">
          <el-input v-model="form.saleNo" placeholder="请输入销售单号" />
        </el-form-item>
        <el-form-item label="销售产品编号" prop="saleProductNo">
          <el-input
            v-model="form.saleProductNo"
            placeholder="请输入销售产品编号"
          />
        </el-form-item>
        <el-form-item label="产品编号" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入产品编号" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品规格" prop="productSpecifications">
          <el-input
            v-model="form.productSpecifications"
            placeholder="请输入产品规格"
          />
        </el-form-item>
        <el-form-item label="产品等级" prop="productLevel">
          <el-input v-model="form.productLevel" placeholder="请输入产品等级" />
        </el-form-item>
        <el-form-item label="产品颜色" prop="productColour">
          <el-input v-model="form.productColour" placeholder="请输入产品颜色" />
        </el-form-item>
        <el-form-item label="批号" prop="lotNumber">
          <el-input v-model="form.lotNumber" placeholder="请输入批号" />
        </el-form-item>
        <el-form-item label="箱数" prop="boxNum">
          <el-input v-model="form.boxNum" placeholder="请输入箱数" />
        </el-form-item>
        <el-form-item label="重量" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>
        <el-form-item label="产品单价" prop="productPrice">
          <el-input v-model="form.productPrice" placeholder="请输入产品单价" />
        </el-form-item>
        <el-form-item label="应收金额" prop="amountReceivable">
          <el-input
            v-model="form.amountReceivable"
            placeholder="请输入应收金额"
          />
        </el-form-item>
        <el-form-item label="已收金额" prop="receivedAmount">
          <el-input
            v-model="form.receivedAmount"
            placeholder="请输入已收金额"
          />
        </el-form-item>
        <el-form-item label="金额" prop="amounts">
          <el-input v-model="form.amounts" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="付款方式" prop="paymentMethod">
          <el-input v-model="form.paymentMethod" placeholder="请输入付款方式" />
        </el-form-item>
        <el-form-item label="应收账备注" prop="accountsReceivableRemark">
          <el-input
            v-model="form.accountsReceivableRemark"
            placeholder="请输入应收账备注"
          />
        </el-form-item>
        <el-form-item label="结算单位" prop="settlementUnit">
          <el-input
            v-model="form.settlementUnit"
            placeholder="请输入结算单位"
          />
        </el-form-item>
        <el-form-item label="回单" prop="returnReceipt">
          <el-input v-model="form.returnReceipt" placeholder="请输入回单" />
        </el-form-item>
        <el-form-item label="回单日期" prop="returnReceiptDate">
          <el-date-picker
            clearable
            v-model="form.returnReceiptDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择回单日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="回单备注" prop="returnReceiptRemark">
          <el-input
            v-model="form.returnReceiptRemark"
            placeholder="请输入回单备注"
          />
        </el-form-item>
        <el-form-item label="通知单号" prop="noticeNumber">
          <el-input v-model="form.noticeNumber" placeholder="请输入通知单号" />
        </el-form-item>
        <el-form-item label="备用列1" prop="spare1">
          <el-input v-model="form.spare1" placeholder="请输入备用列1" />
        </el-form-item>
        <el-form-item label="备用列2" prop="spare2">
          <el-input v-model="form.spare2" placeholder="请输入备用列2" />
        </el-form-item>
        <el-form-item label="备用列3" prop="spare3">
          <el-input v-model="form.spare3" placeholder="请输入备用列3" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="创建者ID" prop="createById">
          <el-input v-model="form.createById" placeholder="请输入创建者ID" />
        </el-form-item>
        <el-form-item label="更新者ID" prop="updateById">
          <el-input v-model="form.updateById" placeholder="请输入更新者ID" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </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>
    <!-- 回单弹窗 -->
    <el-dialog title="回单登记" :visible.sync="receiptShow" width="500px">
      <el-form
        ref="returnReceiptForm"
        :model="returnReceiptForm"
        :rules="receiptFormrules"
        label-width="80px"
      >
        <el-form-item label="回单号" prop="receiptNo">
          <el-input
            v-model="returnReceiptForm.receiptNo"
            placeholder="请输入回单号"
          />
        </el-form-item>
        <el-form-item label="客户" prop="customId">
          <el-select
            v-model="returnReceiptForm.customId"
            placeholder="请选择回单客户"
            clearable
            filterable
          >
            <el-option
              v-for="item in customSelectData"
              :key="item.id"
              :label="item.customName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收到回单" prop="isReceive">
          <el-radio-group v-model="returnReceiptForm.isReceive">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="回单日期" prop="receiveDate">
          <el-date-picker
            v-model="returnReceiptForm.receiveDate"
            type="date"
            size="normal"
            placeholder="选择回单日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="receiveRemark">
          <el-input
            v-model="returnReceiptForm.receiveRemark"
            size="normal"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="receiptShow = false">取 消</el-button>
        <el-button type="primary" @click="submitReceiptForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSaleAccountsReceivableDetail,
  getSaleAccountsReceivableDetail,
  delSaleAccountsReceivableDetail,
  addSaleAccountsReceivableDetail,
  updateSaleAccountsReceivableDetail,
} from "@/api/system/SaleAccountsReceivableDetail";
import { getCustomList } from "@/api/system/SaleRegistrationCollection";
import moment from "moment";

export default {
  name: "saleAccountsReceivableDetail",
  dicts: ["accounting_type", "accounts_receivable_billing_type"],
  data() {
    return {
      receiptIds: [], //回单ids
      receiptShow: false, //回单弹窗
      timeRange: [], //日期范围
      customSelectData: [], //客户list
      returnReceiptForm: {
        receiptNo: "", //回单号
        customId: "", //客户id
        isReceive: true, //收到回单
        receiveDate: "", //回单日期
        receiveRemark: "", //回单备注
      }, //回单
      receiptFormrules: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应收账明细表格数据
      SaleAccountsReceivableDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        accountingType: null,
        customerId: null,
        accountsReceivableDate: null,
        saleNo: null,
        saleProductNo: null,
        productId: null,
        productName: null,
        productSpecifications: null,
        productLevel: null,
        productColour: null,
        lotNumber: null,
        boxNum: null,
        weight: null,
        productPrice: null,
        amountReceivable: null,
        receivedAmount: null,
        amounts: null,
        paymentMethod: null,
        billingType: null,
        accountsReceivableRemark: null,
        settlementUnit: null,
        returnReceipt: null,
        returnReceiptDate: null,
        returnReceiptRemark: null,
        noticeNumber: null,
        status: 2,
        spare1: null,
        spare2: null,
        spare3: null,
        startTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.initSelectData();
  },
  methods: {
    // 根据字典value获取字典label
    getDictLabel(value, dict) {
      return (
        this.dict.type[dict].find((item) => {
          return item.value === value;
        })?.label || ""
      );
    },
    // 修改回单数据
    async returnReceiptChange(row) {
      try {
        let payLoad = {
          id: row.id,
          returnReceipt: row.returnReceipt,
          returnReceiptDate:
            row.returnReceipt == "1" ? row.returnReceiptDate || new Date() : "",
          returnReceiptRemark:
            row.returnReceipt == "1" ? row.returnReceiptRemark || "" : "",
        };
        let res = await updateSaleAccountsReceivableDetail(payLoad);
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.getList();
        } else {
          throw new Error(res.msg);
        }
      } catch (error) {
        this.$message.error(error);
      }
    },

    // 单元格点击回调
    cellClick(row, column, cell, event) {
      console.log(row, column, cell, event);
      let columnList = ["returnReceiptDate", "returnReceiptRemark"];
      if (columnList.includes(column.property)) {
        row[column.property + "Show"] = true;
      }
    },
    // 提交回单回调
    submitReceiptForm() {},
    // 回单回调
    handlerReceipt(id) {
      // let ids=[id]||this.ids;
      this.receiptIds = [id] || this.ids;
      this.receiptShow = true;
    },
    // 日期范围改变回调
    timeRangeChange(val) {
      this.queryParams.startTime = moment(val[0]).format("YYYY-MM-DD");
      this.queryParams.endTime = moment(val[1]).format("YYYY-MM-DD");
      this.handleQuery();
    },
    // 初始化下拉框选择数据
    async initSelectData() {
      // 客户数据
      try {
        let res1 = await getCustomList({ isEnablePaging: false });
        if (res1.code == 200) {
          this.customSelectData = res1.rows;
        } else {
          throw new Error(res1.msg);
        }
      } catch (error) {
        this.$message.error(error);
      }
    },
    /** 查询应收账明细列表 */
    getList() {
      this.loading = true;
      listSaleAccountsReceivableDetail(this.queryParams).then((response) => {
        this.SaleAccountsReceivableDetailList = response.rows.map((item) => {
          return {
            ...item,
            returnReceiptDateShow: false,
            returnReceiptRemarkShow: false,
          };
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        accountingType: null,
        customerId: null,
        accountsReceivableDate: null,
        saleNo: null,
        saleProductNo: null,
        productId: null,
        productName: null,
        productSpecifications: null,
        productLevel: null,
        productColour: null,
        lotNumber: null,
        boxNum: null,
        weight: null,
        productPrice: null,
        amountReceivable: null,
        receivedAmount: null,
        amounts: null,
        paymentMethod: null,
        billingType: null,
        accountsReceivableRemark: null,
        settlementUnit: null,
        returnReceipt: null,
        returnReceiptDate: null,
        returnReceiptRemark: null,
        noticeNumber: null,
        status: null,
        spare1: null,
        spare2: null,
        spare3: null,
        remark: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        delFlag: 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.open = true;
      this.title = "添加应收账明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getSaleAccountsReceivableDetail(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改应收账明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateSaleAccountsReceivableDetail(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSaleAccountsReceivableDetail(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 delSaleAccountsReceivableDetail(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/SaleAccountsReceivableDetail/export",
        {
          ...this.queryParams,
        },
        `SaleAccountsReceivableDetail_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
