<template>
  <div class="borderless" v-loading="pageLoading">
    <div class="customer-head">
      <div class="customer-back">
        <!--        <i class="back-icon el-icon-arrow-left"></i><i style="font-style:normal">返回管理列表</i>-->
        <el-button
          type="danger"
          style="border: none;background: none;color: red"
          icon="el-icon-arrow-left"
          @click="backToList"
          >返回列表
        </el-button>
      </div>
      <div class="add-customer-btn" v-if="showBut">
        <el-button
          type="primary"
          :disabled="detailData.status == 1"
          v-if="detailData.status != 1"
          @click="editCustomer('submit')"
          size="small"
          >提交
        </el-button>
        <el-button
          type="primary"
          :disabled="detailData.status == 1"
          @click="editCustomer('save')"
          :loading="subLoading"
          v-if="detailData.status != 1"
          size="small"
          >{{ form.id ? "确认修改" : "确认新增" }}
        </el-button>
      </div>
    </div>
    <div class="customer-main">
      <containerTitle title="基础信息"></containerTitle>
      <basic-container>
        <avue-form
          ref="form"
          class="trading-form"
          v-model="form"
          :option="option"
        >
          <template slot="corpId">
            <select-component
              v-model="form.corpId"
              :configuration="configuration"
              :disabled="detailData.status == 1"
            ></select-component>
          </template>
        </avue-form>
      </basic-container>
      <containerTitle title="商品信息"></containerTitle>
      <basic-container>
        <avue-crud
          ref="crud"
          :data="data"
          :option="tableOption"
          @row-del="rowDel"
          @saveColumn="saveColumn"
          :summary-method="summaryMethod"
        >
          <template slot="cname" slot-scope="{ row, index }">
            <el-button
              size="small"
              type="text"
              @click="rePick(row, index)"
              :disabled="detailData.status == 1"
              class="picker"
              style="padding:4px 10px;float:left"
              >选择</el-button
            >
            <span> {{ row.cname }}</span>
          </template>
          <template slot="price" slot-scope="{ row }">
            <el-input
              v-if="row.$cellEdit"
              v-model="row.price"
              size="small"
              oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
              @change="priceChange(row)"
            ></el-input>
            <span v-else>{{ row.price }}</span>
          </template>
          <template slot="orderQuantity" slot-scope="{ row }">
            <el-input
              v-if="row.$cellEdit"
              v-model="row.orderQuantity"
              size="small"
              oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
              @change="quantityChange(row)"
            ></el-input>
            <span v-else>{{ row.orderQuantity }}</span>
          </template>
          <template slot="itemType" slot-scope="{ row }">
            <el-select
              v-if="row.$cellEdit"
              v-model="row.itemType"
              filterable
              allow-create
              default-first-option
              placeholder="请输入"
              @focus="itemTypeFocus(row)"
            >
              <el-option
                v-for="(item, index) in itemtypeList"
                :key="index"
                :label="item.value"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <span v-else>{{ row.itemType }}</span>
          </template>
          <template slot="priorityReferrer" slot-scope="{ row }">
            <el-checkbox
              :disabled="!row.$cellEdit"
              v-model="row.priorityReferrer"
              :true-label="1"
              :false-label="0"
            />
          </template>
          <template slot="corpId" slot-scope="{ row, index }">
            <customer-dialog
              v-if="row.$cellEdit"
              v-model="row.corpName"
              :cropIndex="index"
              @getcorpId="getcorpId"
            ></customer-dialog>
            <span v-else>{{ row.corpName }}</span>
          </template>
          <template slot="purchaseAmount" slot-scope="{ row }">
            <el-input
              v-if="row.$cellEdit"
              v-model="row.purchaseAmount"
              size="small"
              oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
            ></el-input>
            <span v-else>{{ row.purchaseAmount | micrometerFormat }}</span>
          </template>
          <template slot="menuLeft">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click.stop="newDetails"
              :disabled="detailData.status == 1"
              >新增明细</el-button
            >
            <el-button
              type="info"
              icon="el-icon-printer"
              size="small"
              @click.stop="openReport()"
              :disabled="detailData.status == 1"
              >报 表</el-button
            >
          </template>
          <template slot="menu" slot-scope="{ row, index }">
            <el-button
              size="small"
              icon="el-icon-edit"
              type="text"
              @click="rowCell(row, index)"
              :disabled="detailData.status == 1"
              >{{ row.$cellEdit ? "保存" : "修改" }}</el-button
            >
            <el-button
              size="small"
              icon="el-icon-edit"
              type="text"
              @click="rowDel(row, index)"
              :disabled="detailData.status == 1"
              >删 除</el-button
            >
          </template>
        </avue-crud>
      </basic-container>
    </div>
    <el-dialog
      title="导入商品"
      append-to-body
      class="el-dialogDeep"
      :visible.sync="dialogVisible"
      width="60%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false"
      @close="closeGoods"
      top="10vh"
    >
      <span>
        <el-row>
          <el-col :span="5">
            <div>
              <el-scrollbar>
                <basic-container style="margin-top:45px">
                  <avue-tree :option="treeOption" @node-click="nodeClick" />
                </basic-container>
              </el-scrollbar>
            </div>
          </el-col>
          <el-col :span="19">
            <avue-crud
              :option="goodsOption"
              :table-loading="loading"
              :data="goodsList"
              ref="goodsCrud"
              @refresh-change="refreshChange"
              @selection-change="selectionChange"
              @row-click="rowClick"
              :page.sync="page"
              @on-load="onLoad"
              @saveColumn="saveGoodsColumn"
            ></avue-crud>
          </el-col>
        </el-row>
      </span>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="importGoods"
          :disabled="selectionList.length == 0"
          >导入</el-button
        >
      </span>
    </el-dialog>
    <report-dialog
      :switchDialog="switchDialog"
      :reportId="form.id"
      reportName="客户询价"
      @onClose="onClose()"
    ></report-dialog>
  </div>
</template>

<script>
import tableOption from "./config/customerContact.json";
import goodsOption from "./config/commodity.json";
import {
  detail,
  submit,
  delItem,
  getDeptLazyTree,
  getGoods,
  getSpecification,
  submitMessage
} from "@/api/basicData/purchaseInquiry";
import customerDialog from "@/components/customer-dialog/main";
import reportDialog from "@/components/report-dialog/main";
import { micrometerFormat } from "@/util/validate";
import { contrastObj, contrastList } from "@/util/contrastData";
import _ from "lodash";
export default {
  name: "detailsPageEdit",
  data() {
    return {
      configuration: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: "请点击右边按钮选择",
        dicData: []
      },
      switchDialog: false,
      form: {
        orderStatus: "录入"
      },
      disabled: false,
      dialogVisible: false,
      tableOption: {},
      option: {
        menuBtn: false,
        labelWidth: 100,
        disabled: false,
        column: [
          {
            label: "客户名称",
            prop: "corpId",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 16,
            slot: true
          },
          {
            label: "系统号",
            prop: "sysNo",
            span: 8
          },
          {
            label: "订单状态",
            prop: "orderStatus",
            span: 8,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=order_status",
            props: {
              label: "dictValue",
              value: "dictValue"
            }
          },
          {
            label: "询价日期",
            prop: "businesDate",
            span: 8,
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd 00:00:00"
          },
          {
            label: "有效日期",
            prop: "dateValidity",
            span: 8,
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd 00:00:00"
          },
          {
            label: "订单号",
            prop: "orderNo",
            span: 8
          },
          {
            label: "币别",
            prop: "currency",
            span: 8,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=currency",
            props: {
              label: "dictValue",
              value: "dictValue"
            },
            change: ({ value }) => {
              if (value == "CNY") {
                this.form.exchangeRate = 1;
              }
              if (value == "USD") {
                this.form.exchangeRate = 6.3843;
              }
            }
          },
          {
            label: "汇率",
            prop: "exchangeRate",
            span: 8,
            slot: true,
            row: true,
            disabled: true
          },
          {
            label: "备注",
            prop: "orderRemark",
            type: "textarea",
            minRows: 2,
            span: 8
          },
          {
            label: "采购备注",
            prop: "purchaseRemark",
            type: "textarea",
            minRows: 2,
            span: 8
          },
          {
            label: "船务备注",
            prop: "shippingRemark",
            type: "textarea",
            minRows: 2,
            span: 8
          }
        ]
      },
      treeOption: {
        nodeKey: "id",
        lazy: true,
        treeLoad: function(node, resolve) {
          const parentId = node.level === 0 ? 0 : node.data.id;
          getDeptLazyTree(parentId).then(res => {
            resolve(
              res.data.data.map(item => {
                return {
                  ...item,
                  leaf: !item.hasChildren
                };
              })
            );
          });
        },
        addBtn: false,
        menu: false,
        size: "small",
        props: {
          label: "title",
          value: "value",
          children: "children"
        }
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      loading: false,
      goodsOption: {},
      data: [],
      goodsList: [],
      selectionList: [],
      treeDeptId: null,
      itemtypeList: [],
      reData: null,
      oldform: {
        orderStatus: "录入"
      },
      olddata: [],
      subLoading: false,
      pageLoading: false,
      showBut: true
    };
  },
  props: {
    detailData: {
      type: Object
    }
  },
  components: {
    reportDialog,
    customerDialog
  },
  async created() {
    if (this.detailData.id) {
      this.getDetail(this.detailData.id);
    }
    this.tableOption = await this.getColumnData(
      this.getColumnName(11),
      tableOption
    );
    this.goodsOption = await this.getColumnData(
      this.getColumnName(31),
      goodsOption
    );
    if (this.detailData.status == 1) {
      this.option.disabled = true;
    }
    this.getWorkDicts("product_properties").then(res => {
      this.findObject(this.tableOption.column, "itemProp").dicData =
        res.data.data;
    });
    this.getWorkDicts("unit").then(res => {
      this.findObject(this.tableOption.column, "unit").dicData = res.data.data;
    });
  },
  methods: {
    cellStyle() {
      return "padding:0;height:40px;";
    },
    rePick(row, index) {
      this.reData = {
        ...row,
        index: index
      };
      this.newDetails();
    },
    getcorpId(row) {
      console.log(row);
      this.data[row.index].corpId = row.id;
    },
    rowCell(row, index) {
      if (row.$cellEdit == true) {
        this.$set(row, "$cellEdit", false);
      } else {
        this.$set(row, "$cellEdit", true);
      }
    },
    itemTypeFocus(row) {
      this.itemtypeList = [];
      getSpecification({ goodId: row.itemId }).then(res => {
        const data = res.data.data;
        this.itemtypeList = data.map(item => ({ value: item }));
      });
    },
    priceChange(row) {
      console.log(row);
      if (!row.price) {
        row.price = 0;
      } else {
        row.amount = _.multiply(row.price, row.orderQuantity).toFixed(2);
      }
    },
    quantityChange(row) {
      if (!row.orderQuantity) {
        row.orderQuantity = 0;
      } else {
        row.amount = _.multiply(row.price, row.orderQuantity).toFixed(2);
      }
    },
    rowSave(row) {
      console.log(row);
      this.$set(row, "$cellEdit", false);
    },
    rowDel(row, index) {
      if (row.id) {
        delItem(row.id).then(res => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.data.splice(index, 1);
        });
      } else {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.data.splice(index, 1);
      }
    },
    importGoods() {
      if (this.reData) {
        console.log(this.reData);
        if (this.selectionList.length != 1) {
          return this.$message.error("重新选择的时候只能选择一条数据");
        } else {
          this.selectionList.forEach(e => {
            this.data.forEach((item, index) => {
              if (index == this.reData.index) {
                item.itemId = e.id;
                item.code = e.code;
                item.cname = e.cname;
                item.priceCategory = e.goodsTypeName;
                item.itemUrl = e.url;
                item.itemProp = this.reData.itemProp;
                item.itemDescription = e.cnameDescription;
                item.itemType = this.reData.itemType;
                item.tradeTerms = this.reData.tradeTerms;
                item.price = this.reData.price;
                item.orderQuantity = this.reData.orderQuantity;
                item.insurance = this.reData.insurance;
                item.freight = this.reData.freight;
                item.discount = this.reData.discount;
                item.amount = this.reData.amount;
                item.taxRate = this.reData.taxRate;
                item.unit = e.unit;
                item.remarks = this.reData.remarks;
                item.$cellEdit = true;
              }
            });
          });
        }
      } else {
        this.selectionList.forEach(e => {
          this.data.push({
            itemId: e.id,
            code: e.code,
            cname: e.cname,
            priceCategory: e.goodsTypeName,
            itemUrl: e.url,
            itemProp: null,
            itemDescription: e.cnameDescription,
            itemType: null,
            tradeTerms: null,
            price: 0,
            orderQuantity: 0,
            insurance: 0,
            freight: 0,
            discount: null,
            amount: 0,
            taxRate: 0,
            unit: e.unit,
            remarks: null,
            $cellEdit: true
          });
        });
      }
      this.dialogVisible = false;
    },
    closeGoods() {
      this.selectionList = [];
      this.treeDeptId = "";
      this.reData = null;
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    rowClick(row) {
      this.$refs.goodsCrud.toggleSelection([this.goodsList[row.$index]]);
    },
    nodeClick(data) {
      this.treeDeptId = data.id;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //费用查询
    onLoad(page, params = {}) {
      this.loading = true;
      getGoods(page.currentPage, page.pageSize, this.treeDeptId).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.goodsList = data.records;
        this.loading = false;
        if (this.page.total) {
          this.goodsOption.height = window.innerHeight - 550;
        } else {
          this.goodsOption.height = window.innerHeight - 475;
        }
      });
    },
    //商品明细导入
    newDetails() {
      this.dialogVisible = !this.dialogVisible;
    },
    getDetail(id) {
      this.showBut = false;
      this.pageLoading = true;
      detail(id)
        .then(res => {
          this.form = res.data.data;
          this.data = res.data.data.orderItemsList
            ? res.data.data.orderItemsList
            : [];
          this.configuration.dicData = this.form.corpsName;
          this.oldform = res.data.data;
          this.olddata = this.deepClone(
            res.data.data.orderItemsList ? res.data.data.orderItemsList : []
          );
        })
        .finally(() => {
          this.showBut = true;
          this.pageLoading = false;
        });
    },
    //修改提交触发
    editCustomer(status, status2) {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          if (status == "save") {
            this.subLoading = true;
            submit({
              ...this.form,
              orderItemsList: this.data
            })
              .then(res => {
                this.form = res.data.data;
                this.data = res.data.data.orderItemsList
                  ? res.data.data.orderItemsList
                  : [];
                this.configuration.dicData = this.form.corpsName;
                this.$message.success("修改成功");
                this.oldform = res.data.data;
                this.olddata = this.deepClone(
                  res.data.data.orderItemsList
                    ? res.data.data.orderItemsList
                    : []
                );
                if (status2 == "goBack") {
                  this.$emit("goBack");
                }
              })
              .finally(() => {
                this.subLoading = false;
              });
          }
          if (status == "submit") {
            submitMessage({
              ...this.form,
              orderItemsList: this.data
            }).then(res => {
              this.form = res.data.data;
              this.data = res.data.data.orderItemsList
                ? res.data.data.orderItemsList
                : [];
              this.configuration.dicData = this.form.corpsName;
              this.$message.success("提交成功");
              this.oldform = res.data.data;
              this.olddata = this.deepClone(
                res.data.data.orderItemsList ? res.data.data.orderItemsList : []
              );
            });
          }
        } else {
          return false;
        }
      });
    },
    //返回列表
    backToList() {
      if (
        contrastObj(this.form, this.oldform) ||
        contrastList(this.data, this.olddata)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否提交?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.editCustomer("save", "goBack");
          })
          .catch(() => {
            this.$emit("goBack");
          });
      } else {
        this.$emit("goBack");
      }
    },
    openReport() {
      this.switchDialog = !this.switchDialog;
    },
    onClose(val) {
      this.switchDialog = val;
    },
    summaryMethod({ columns, data }) {
      const sums = [];
      if (columns.length > 0) {
        columns.forEach((item, index) => {
          sums[0] = "合计";
          if (item.property == "orderQuantity" || item.property == "amount") {
            let qtySum = 0;
            let amountSum = 0;
            data.forEach(e => {
              qtySum = _.add(qtySum, Number(e.orderQuantity));
              amountSum = _.add(amountSum, Number(e.amount));
            });
            //数量总计
            if (item.property == "orderQuantity") {
              sums[index] = qtySum ? qtySum.toFixed(2) : "0.00";
            }
            //金额总计
            if (item.property == "amount") {
              sums[index] = micrometerFormat(amountSum);
            }
          }
        });
      }
      return sums;
    },
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(11),
        this.tableOption
      );
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    async saveGoodsColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(31),
        this.goodsOption
      );
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.goodsCrud.$refs.dialogColumn.columnBox = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.trading-form ::v-deep .el-form-item {
  margin-bottom: 8px !important;
}
::v-deep .el-form-item__error {
  display: none !important;
}
::v-deep .select-component {
  display: flex !important;
}
</style>
