<template>
  <div>
    <div class="borderless">
      <div class="customer-head">
        <div class="customer-back">
          <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">
          <el-button v-if="detailData.check" type="primary" size="small" class="el-button--small-yh"
                     @click.stop="openCheckDialog">
            审批
          </el-button>
          <el-button type="info" icon="el-icon-printer" size="small" @click.stop="openReport()">报表打印
          </el-button>
          <el-button type="primary" size="small" v-if="detailData.status == 1 && form.confirmStatus == 0"
                     class="el-button--small-yh " @click.stop="openEdit">编辑
          </el-button>
          <el-button type="primary" size="small" v-if="!form.id && detailData.status != 1" @click="editCustomer">
            保存数据
          </el-button>
          <el-button type="primary" size="small" v-if="form.id && detailData.status != 1 && form.confirmStatus == 0"
                     @click="fixSave">
            保存数据
          </el-button>
          <el-button type="primary" size="small" v-if="form.id && detailData.status != 1 && form.confirmStatus == 0"
            @click="submit">
            提交
          </el-button>
          <el-button type="primary" size="small" v-if="form.confirmStatus == 1" @click="revokeOrder">
            撤销
          </el-button>

        </div>
      </div>
      <!-- <containerTitle title="基础资料" style="margin-top: 60px"></containerTitle> -->
      <trade-card title="基础资料" style="margin-top: 60px" v-loading="loadingBtn">
        <avue-form ref="form" class="trading-form" v-model="form" :option="option">
          <template slot="corpId">
            <crop-select v-model="form.corpId" corpType="KH" :disabled="detailData.status == 1"
              @getCorpData="getCorpData"></crop-select>
          </template>
          <template slot="storageId">
            <el-select v-model="form.storageId" placeholder="请选择" size="small" filterable @change="storageChange"
              :disabled="detailData.status == 1 || data.length > 0">
              <el-option v-for="item in storageoptions" :key="item.id" :label="item.cname" :value="item.id">
              </el-option>
            </el-select>
          </template>
        </avue-form>
      </trade-card>
      <trade-card title="商品信息" v-loading="loadingBtn">
        <avue-form class="trading-form" v-model="form" :option="option2">
          <template slot="thisUsedProfit">
            <el-input-number v-model="form.thisUsedProfit" :disabled="detailData.status == 1" @change="amountChange"
              placeholder="请输入" size="small" :controls="false" style="width:100%;"></el-input-number>
          </template>
        </avue-form>
        <avue-crud ref="crud" :option="optionList" :data="data" :table-loading="loading" @saveColumn="saveColumn"
          @resetColumn="resetColumn" :cell-style="cellStyle">
          <template slot="headerSerial">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click.stop="addRow"
              :disabled="detailData.status == 1" circle></el-button>
          </template>
          <template slot="cname" slot-scope="{ row, index }">
            <el-select v-if="row.$cellEdit" v-model="row.cname" placeholder="请选择" size="small" filterable
              @change="cnameChange(row, index)">
              <el-option v-for="item in goodsoptions" :key="item.itemId" :label="item.cname" :value="item.cname"
                :disabled="item.status == 1">
              </el-option>
            </el-select>
            <span v-else>{{ row.cname }}</span>
          </template>
          <template slot="unitHeader" slot-scope="{column}">
            <span style="color: #409EFF;cursor: pointer" @click.stop="$refs.dictbiz.open()">单位
            </span>
          </template>
          <template slot="storageInQuantity" slot-scope="{ row, index }">
            <el-input-number v-if="row.$cellEdit" v-model="row.storageInQuantity" @change="countChange(row)"
              placeholder="请输入" size="small" :controls="false" style="width:100%;"></el-input-number>
            <span v-else>{{ row.storageInQuantity }}</span>
          </template>
          <template slot="price" slot-scope="{ row, index }">
            <el-input-number v-if="row.$cellEdit" v-model="row.price" @change="countChange(row)" placeholder="请输入"
              size="small" :controls="false" style="width:100%;"></el-input-number>
            <span v-else>{{ row.price }}</span>
          </template>
          <template slot="purchaseAmount" slot-scope="{ row, index }">
            <el-input-number v-if="row.$cellEdit" v-model="row.purchaseAmount" @change="countChange(row)"
              placeholder="请输入" size="small" :controls="false" style="width:100%;"></el-input-number>
            <span v-else>{{ row.purchaseAmount }}</span>
          </template>
          <template slot="menu" slot-scope="{ row, index }">
            <el-button size="small" type="text" :disabled="detailData.status == 1" @click="rowCell(row, index)">{{
                row.$cellEdit ? "保存" : "修改"
            }}</el-button>
            <el-button size="small" type="text" :disabled="detailData.status == 1" @click="rowDel(row, index)">删除
            </el-button>
          </template>
        </avue-crud>
      </trade-card>
      <fee-info ref="feeInfo" :data="settlementList" :form="form" :detailData="detailData" @getPay="getPay"
        v-loading="loadingBtn">
      </fee-info>
      <containerTitle title="上传附件"></containerTitle>
      <c-upload v-loading="loadingBtn" typeUpload="CD"
        deleteUrl="/api/trade-purchase/woodHarvestingCloud/removeByFileId" :data="orderFilesList" display
        :enumerationValue="35.1" :disabled="detailData.status == 1"></c-upload>
      <el-dialog :title="addressTitle" v-dialogDrag :visible.sync="addressVisible" class="avue-dialog avue-dialog--top"
        width="50%" append-to-body>
        <span>
          <el-tabs v-model="activeName">
            <el-tab-pane label="客户地址" name="first">
              <avue-form class="trading-form" v-model="form2" :option="optiontabs1"></avue-form>
            </el-tab-pane>
            <el-tab-pane label="物流地址" name="second">
              <avue-form class="trading-form" v-model="form3" :option="optiontabs2"></avue-form>
            </el-tab-pane>
          </el-tabs>
        </span>
        <div class="avue-dialog__footer">
          <el-button @click="addressVisible = false">取 消</el-button>
          <el-button @click="addressVisible = false" type="primary">确 定</el-button>
        </div>
      </el-dialog>
      <dictbiz-dialog ref="dictbiz" title="添加单位" code="unit" parentId="1585962784498225154"
                      @closed="getAllWorkDicts">
      </dictbiz-dialog>
      <report-dialog :switchDialog="switchDialog" :reportId="form.id" reportName="配件系统-销售单" @onClose="onClose()">
      </report-dialog>
    </div>
    <el-dialog append-to-body title="审批" class="el-dialogDeep" :visible.sync="checkDialog" width="50%"
               :close-on-click-modal="false" :destroy-on-close="true" :close-on-press-escape="false" v-dialog-drag>
      <check :checkData="checkData" :checkDetail="false" :idList="[]" @choceCheckFun="choceCheckFun">
      </check>
    </el-dialog>
  </div>
</template>

<script>
import {optionList} from "./js/optionList";
import {
  getDetails,
  submit,
  getCorpDetails,
  remove,
  getAllgoods,
  save,
  fixSave,
  revoke,
  collectPayment,
  getStoragelist,
  offset
} from "@/api/basicData/salesOrder";
import feeInfo from "./components/feeInfo.vue";
import reportDialog from "@/components/report-dialog/main";
import { multiply, sum, subtract } from "@/util/calculate";
import {fdatasync} from "fs";
import check from "@/components/check/check";
export default {
  name: "index",
  data() {
    return {
      checkDialog: false,
      checkData: {},
      switchDialog: false,
      activeName: 'first',
      loadingBtn: false,
      addressTitle: null,
      addressVisible: false,
      form: {},
      form2: {},
      form3: {

      },
      data: [],
      option: {
        menuBtn: false,
        labelWidth: 90,
        disabled: false,
        column: [
          {
            label: "客户名称",
            prop: "corpId",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 8,
          },
          {
            label: "送货地址",
            prop: "arrivalAddress",
            type: 'select',
            dicData: [],
            props: {
              label: 'detailedAddress',
              value: 'detailedAddress'
            },
            allowCreate: true,
            filterable: true,
            span: 16,
          },
          {
            label: "销售日期",
            prop: "businesDate",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd 00:00:00",
            span: 8,
          },
          {
            label: "计划收款日期",
            prop: "advanceCollectionDate",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd 00:00:00",
            span: 8,
          },
          {
            label: "送货日期",
            prop: "requiredDeliveryDate",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd 00:00:00",
            span: 8,
          },
          {
            label: "仓库",
            prop: "storageId",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 8,
          },
          {
            label: "备注",
            prop: "orderRemark",
            placeholder: "打印时显示",
            type: "textarea",
            minRows: 3,
            span: 16,
          }
        ]
      },
      option2: {
        menuBtn: false,
        labelWidth: 80,
        disabled: false,
        column: [
          {
            label: "税率",
            prop: "exchangeRate",
            type: "select",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=tax_rate",
            span: 4,
          },
          {
            label: "销售总数量",
            prop: "storageQuantity",
            disabled: true,
            span: 4,
          },
          {
            label: "成本",
            prop: "costAmount",
            disabled: true,
            span: 4,
          },
          {
            label: "毛利",
            prop: "grossProfit",
            disabled: true,
            span: 4,
          },
          {
            label: "订单金额",
            prop: "purchaseAmount",
            disabled: true,
            span: 4,
          },
          {
            label: "优惠金额",
            prop: "thisUsedProfit",
            span: 4,
          },
          {
            label: "合同金额",
            prop: "orderAmount",
            disabled: true,
            span: 8,
          },
          {
            label: "应收金额",
            prop: "balanceAmount",
            disabled: true,
            span: 8,
          },
          {
            label: "已收金额",
            prop: "settlmentAmount",
            disabled: true,
            span: 8,
          }
        ]
      },
      optiontabs1: {
        menuBtn: false,
        labelWidth: 90,
        column: [
          {
            label: "简称",
            prop: "a",
            type: "select",
            span: 24,
          },
          {
            label: "地址",
            prop: "b",
            type: "select",
            span: 24,
          },
          {
            label: "详细地址",
            prop: "c",
            span: 24,
          },
          {
            label: "邮编",
            prop: "d",
            span: 24,
          },
          {
            label: "备注",
            prop: "e",
            type: 'textarea',
            minRows: 3,
            span: 24,
          },
          {
            label: "地址智能识别",
            prop: "ad",
            placeholder: "例：上海市徐汇区枫林街道斜土路100号",
            type: "textarea",
            minRows: 3,
            span: 24,
          }
        ]
      },
      optiontabs2: {
        menuBtn: false,
        labelWidth: 80,
        column: [
          {
            label: "目的地",
            prop: "a",
            type: "select",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 24,
          },
          {
            label: "物流公司",
            prop: "b",
            span: 24,
          },
          {
            label: "电话",
            prop: "c",
            span: 24,
          },
          {
            label: "地址",
            prop: "d",
            span: 24,
          },
          {
            label: "详细地址",
            prop: "e",
            span: 24,
          },
          {
            label: "邮编",
            prop: "f",
            span: 24,
          },
          {
            label: "备注",
            prop: "remarks",
            type: "textarea",
            minRows: 3,
            span: 24,
          },
          {
            label: "地址智能识别",
            prop: "g",
            type: "textarea",
            minRows: 3,
            span: 24,
          }
        ]
      },
      optionList: {},
      goodsoptions: [],
      settlementList: [],
      orderFilesList: [],
      storageoptions: []
    };
  },
  props: {
    detailData: {
      type: Object
    }
  },
  components: {
    feeInfo,
    check,
    reportDialog
  },
  async created() {
    // console.log(this.detailData)
    this.optionList = await this.getColumnData(
      this.getColumnName(212),
      optionList
    );
    if (this.detailData.id) {
      this.getDetail(this.detailData.id);
    }
    if (this.detailData.status == 1) {
      this.option.disabled = true;
      this.option2.disabled = true;
    }
    this.getAllWorkDicts()
    getAllgoods().then(res => {
      this.goodsoptions = res.data.data
    });
  },
  methods: {
    //打开审核
    openCheckDialog() {
      this.checkData = this.detailData.check;
      this.checkDialog = true;
    },
    //关闭审核
    choceCheckFun() {
      this.checkDialog = false;
    },
    openReport() {
      this.switchDialog = !this.switchDialog;
    },
    onClose(val) {
      this.switchDialog = val;
    },
    getAllWorkDicts() {
      this.getWorkDicts("unit").then(res => {
        this.findObject(this.optionList.column, "unit").dicData = res.data.data;
      });
      getStoragelist().then(res => {
        this.storageoptions = res.data;
        this.findObject(this.optionList.column, "storageId").dicData = res.data;
      })
      this.$refs.crud.init();
    },
    cellStyle() {
      return "padding:0;height:40px;";
    },
    cnameChange(row) {
      if (row.cname) {
        this.goodsoptions.forEach(e => {
          if (e.cname == row.cname) {
            row.itemId = e.id
            row.unit = e.unit
            row.price = e.standardPrice
            row.storageInQuantity = 1
            row.amount = e.standardPrice
            row.purchasePrice = e.purchasePrice
            row.storageAmount = e.purchasePrice
          }
        })
      } else {
        row.itemId = null
        row.unit = null
        row.price = null
        row.storageInQuantity = null
        row.amount = null
        row.purchasePrice = null
        row.storageAmount = null
      }
      this.countChange(row)
    },
    amountChange() {
      let val = 0
      this.data.forEach(e => {
        val = sum(val, e.amount)
        this.form.purchaseAmount = val
        this.form.orderAmount = subtract(this.form.purchaseAmount, this.form.thisUsedProfit)
      })
    },
    countChange(row) {
      row.amount = multiply(row.price, row.storageInQuantity)
      row.storageAmount = multiply(row.purchaseAmount, row.storageInQuantity)
      let val = 0
      this.data.forEach(e => {
        val = sum(val, e.amount)
        this.form.purchaseAmount = val
        this.form.orderAmount = subtract(this.form.purchaseAmount, this.form.thisUsedProfit)
      })
      this.$refs.crud.refreshTable();
    },
    getDetail(id) {
      this.loadingBtn = true
      getDetails({ id: id })
        .then(res => {
          this.form = res.data.data;
          this.data = res.data.data.orderItemsList;
          this.settlementList = res.data.data.settlementList;
          this.orderFilesList = res.data.data.orderFilesList ? res.data.data.orderFilesList : [];
          this.getAddress(res.data.data)
        })
        .finally(() => {
          this.loadingBtn = false;
        });
    },
    getCorpData(row) {
      if (row) {
        this.form.corpsName = row.cname
        this.form.corpTel = row.tel
        getCorpDetails({ id: row.id }).then(res => {
          this.findObject(this.option.column, "arrivalAddress").dicData = res.data.data.corpsAddrList;
        })
      } else {
        this.form.corpsName = null
        this.form.corpTel = null
        this.findObject(this.option.column, "arrivalAddress").dicData = []
      }
    },
    storageChange(row) {
      // console.log(row)

    },
    getAddress(row) {
      getCorpDetails({ id: row.corpId }).then(res => {
        this.findObject(this.option.column, "arrivalAddress").dicData = res.data.data.corpsAddrList;
      })
    },
    addRow() {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          this.data.push({ $cellEdit: true, storageId: this.form.storageId })
        } else {
          return false;
        }
      });
    },
    rowCell(row, index) {
      if (row.$cellEdit == true) {
        this.$set(row, "$cellEdit", false);
      } else {
        this.$set(row, "$cellEdit", true);
      }
    },
    rowDel(row, index) {
      this.$confirm("确定删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id) {
          remove(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);
        }
      });
    },
    getPay(row) {
      // this.form = row;
      // this.data = row.orderItemsList;
      // this.settlementList = row.settlementList
      this.getDetail(row.id);
    },
    //修改提交触发
    editCustomer() {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          if (this.data.length == 0) {
            return this.$message.error('请添加一条商品信息');
          }
          if (this.settlementList.length > 0) {
            for (let i = 0; i < this.settlementList.length; i++) {
              if (!this.settlementList[i].id) {
                return this.$message.error(`请保存第${i + 1}行的费用明细`);
              }
            }
          }
          this.loadingBtn = true;
          save({ ...this.form, billType: 'XSJH', tradeType: 'YPJ', orderItemsList: this.data, settlementList: this.settlementList, orderFilesList: this.orderFilesList })
            .then(res => {
              this.$message.success("保存成功");
              this.form = res.data.data;
              this.data = res.data.data.orderItemsList;
              this.settlementList = res.data.data.settlementList;
              this.orderFilesList = res.data.data.orderFilesList ? res.data.data.orderFilesList : [];
              this.detailData.status = 1
              this.option.disabled = true;
              this.option2.disabled = true;
              this.$refs.crud.refreshTable();
              this.$refs.feeInfo.refreshTable();
            })
            .finally(() => {
              this.loadingBtn = false;
            });
        } else {
          return false;
        }
      });
    },
    fixSave() {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          if (this.data.length == 0) {
            return this.$message.error('请添加一条商品信息');
          }
          if (this.settlementList.length > 0) {
            for (let i = 0; i < this.settlementList.length; i++) {
              if (!this.settlementList[i].id) {
                return this.$message.error(`请保存第${i + 1}行的费用明细`);
              }
            }
          }
          this.loadingBtn = true;
          fixSave({ ...this.form, billType: 'XSJH', tradeType: 'YPJ', orderItemsList: this.data, settlementList: this.settlementList, orderFilesList: this.orderFilesList })
            .then(res => {
              this.$message.success("修改成功");
              this.form = res.data.data;
              this.data = res.data.data.orderItemsList;
              this.settlementList = res.data.data.settlementList
              this.orderFilesList = res.data.data.orderFilesList ? res.data.data.orderFilesList : [];
            })
            .finally(() => {
              this.loadingBtn = false;
            });
        } else {
          return false;
        }
      });
    },
    submit() {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          if (this.data.length == 0) {
            return this.$message.error('请添加一条商品信息');
          }
          if (this.settlementList.length > 0) {
            for (let i = 0; i < this.settlementList.length; i++) {
              if (!this.settlementList[i].id) {
                return this.$message.error(`请保存第${i + 1}行的费用明细`);
              }
            }
          }
          this.loadingBtn = true;
          submit({ ...this.form, billType: 'XSJH', tradeType: 'YPJ', orderItemsList: this.data, settlementList: this.settlementList, orderFilesList: this.orderFilesList })
            .then(res => {
              this.$message.success("提交成功");
              this.form = res.data.data;
              this.data = res.data.data.orderItemsList;
              this.settlementList = res.data.data.settlementList;
              this.orderFilesList = res.data.data.orderFilesList ? res.data.data.orderFilesList : [];
              this.$emit("goBack");
            })
            .finally(() => {
              this.loadingBtn = false;
            });
        } else {
          return false;
        }
      });
    },
    revokeOrder() {
      this.$confirm('此操作将会撤销单子, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingBtn = true;
        revoke({ ...this.form, billType: 'XSJH', tradeType: 'YPJ', orderItemsList: this.data, settlementList: this.settlementList })
          .then(res => {
            this.$message.success("撤销成功");
            this.form = res.data.data;
            this.data = res.data.data.orderItemsList;
            this.settlementList = res.data.data.settlementList
            this.openEdit()
          })
          .finally(() => {
            this.loadingBtn = false;
          });
      }).catch(() => {
      });
    },
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(212),
        this.optionList
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    async resetColumn() {
      this.optionList = optionList;
      const inSave = await this.delColumnData(
        this.getColumnName(212),
        optionList
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.getAllWorkDicts()
        this.$message.success("重置成功");
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    openEdit() {
      this.detailData.status = 2
      this.option = this.$options.data().option;
      this.option2 = this.$options.data().option2;
      this.$refs.crud.refreshTable();
      this.$refs.feeInfo.refreshTable();
    },
    //返回列表
    backToList() {
      this.$emit("goBack");
    }
  },
};
</script>

<style lang="scss" scoped>
.trading-form ::v-deep .el-form-item {
  margin-bottom: 8px !important;
}

::v-deep .el-dialog__body {
  padding: 0px 20px 15px 20px;
}

::v-deep .el-form-item__error {
  display: none !important;
}

.img-form ::v-deep .el-form-item {
  height: 150px;
  line-height: 150px;
  margin-bottom: 8px !important;
}

.img-form ::v-deep .avue-upload__icon {
  font-size: 20px;
  width: 150px;
  height: 150px;
  line-height: 150px;
}

::v-deep .el-table .cell {
  padding: 0 2px !important;
}

::v-deep .avue-crud .el-table .el-form-item__label {
  left: -1px;
}

.addressTabs {
  display: flex;
  justify-content: center;

  span {
    width: 100px;
    font-size: 18px;
    font-weight: 600;
    text-align: center;
  }
}
</style>
