<template>
  <div>
    <basic-container v-show="isShow">
      <avue-crud :option="option" :data="dataList" ref="crud" v-model="form" :page.sync="page" :search.sync="search"
        :table-loading="loading" @row-del="rowDel" :before-open="beforeOpen" :before-close="beforeClose"
        @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
        @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad"
        @tree-load="treeLoad" @saveColumn="saveColumn" @resetColumn="resetColumn"
        @search-criteria-switch="searchCriteriaSwitch" :cell-style="cellStyle">
        <template slot="menuLeft" slot-scope="{size}">
          <el-button type="success" :size="size" icon="el-icon-copy-document" @click="copyOrder" :disabled="single">复制单据
          </el-button>
          <el-button type="info" :size="size" icon="el-icon-printer" @click="outExport">导出</el-button>
          <el-button type="warning" :size="size" icon="el-icon-thumb" :disabled="multiple" @click="applyPayment">申请货款
          </el-button>
        </template>
        <template slot-scope="scope" slot="orgOrderNo">
          <span style="color: #409EFF;cursor: pointer" @click.stop="beforeOpenPage(scope.row, scope.index)">{{ scope.row.orgOrderNo }}</span>
        </template>
        <template slot="corpIdSearch">
          <crop-select v-model="search.corpId" corpType="GYS"></crop-select>
        </template>
        <template slot-scope="scope" slot="corpId">
          <span style="color: #409EFF;cursor: pointer" @click.stop="beforeOpenPage(scope.row, scope.index)">{{ scope.row.strCorpName }}</span>
        </template>
        <template slot-scope="scope" slot="orderNo">
          <span style="color: #409EFF;cursor: pointer" @click.stop="beforeOpenPage(scope.row, scope.index)">{{ scope.row.orderNo }}</span>
        </template>
        <template slot-scope="scope" slot="createUser">
          {{ scope.row.createUserName }}
        </template>
        <template slot-scope="scope" slot="createFreight">
          {{ scope.row.createFreight == 1 ? '是' : '否' }}
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button type="text" icon="el-icon-delete" size="small" v-debounce @click.stop="createPlant(scope.row, scope.index)"
            :disabled="scope.row.status > 0 || scope.row.createFreight == 1">生成工厂发货
          </el-button>
          <!--          <el-button-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            size="small"-->
          <!--            @click.stop="editOpen(scope.row,scope.index)"-->
          <!--          >编辑-->
          <!--          </el-button>-->
          <el-button type="text" icon="el-icon-delete" size="small" @click.stop="rowDel(scope.row, scope.index)"
            :disabled="(scope.row.itemsList && scope.row.itemsList.length == 0) || scope.row.createFreight == 1">删除
          </el-button>
        </template>
      </avue-crud>
    </basic-container>

    <detail-page ref="detail" @goBack="goBack" :detailData="detailData" v-if="!isShow"></detail-page>

    <el-dialog title="账单" append-to-body class="el-dialogDeep" :visible.sync="applyPaymentDialog" width="60%"
      :close-on-click-modal="false" :destroy-on-close="true" :close-on-press-escape="false" v-dialog-drag>
      <apply-payment v-if="applyPaymentDialog" :billType="billType" :billData="billData" :arrList="applyPaymentList"
        @choceFun="choceFun">
      </apply-payment>
    </el-dialog>
    <el-dialog append-to-body title="账单" class="el-dialogDeep" :visible.sync="financialAccountDialog" width="70%"
      :close-on-click-modal="false" :destroy-on-close="true" :close-on-press-escape="false" v-dialog-drag>
      <financial-account v-if="financialAccountDialog" :billType="billType" :billData="billData"
        :checkData="financeData" :arrList="applyPaymentList" @choceFun="choceFun" tradeType="GN" @submit="feeSubmit"
        :addBut="false">
      </financial-account>
    </el-dialog>
  </div>
</template>

<script>
import option from "./configuration/mainList.json";
import { customerList, deleteDetails, generateShipment, genfactory, getApplyAmount } from "@/api/basicData/purchaseOrder"
import detailPage from "./detailsPageEdit";
import { defaultDate } from "@/util/date";
import ApplyPayment from "@/components/finance/applyPayment";
import financialAccount from "../../../components/finance/financialAccount";
import { gainUser } from "@/api/basicData/customerInquiry";
import { customerList as feeList } from "@/api/basicData/basicFeesDesc";
import { getCurrentDate } from "@/util/date";
import {getToken} from "@/util/auth";
export default {
  name: "customerInformation",
  props: {
    detailData: {
      type: Object
    }
  },
  components: {
    detailPage,
    ApplyPayment,
    financialAccount
  },
  data() {
    return {
      configuration: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: "请点击右边按钮选择",
        dicData: [],
        clearable: true,
      },
      search: {},
      loading: false,
      form: {},
      option: {},
      parentId: 0,
      dataList: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 50, 100, 200, 300]
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      selection: [],
      isShow: true,
      detailData: {},
      billType: "申请",  //账单类型
      billData: {},     //账单需要数据
      financeData: {
        url: "/financialManagement/paymentRequest/index",
        pageStatus: "this.$store.getters.pqStatus",
        pageLabel: "付费申请",
        checkType: 'ffsq'
      }, // 账单请核需要的路由
      applyPaymentDialog: false,//生成账单组件
      financialAccountDialog: false,
      applyPaymentList: [],
      feesOption: [],
    }
  },
  async created() {
    // this.search.requiredArrivalDate = defaultDate(1)
    this.search.createTime = defaultDate(3)
    // this.option = option
    this.option = await this.getColumnData(this.getColumnName(17), option);
    this.getWorkDicts("payment_term").then(res => {
      this.findObject(this.option.column, "paymentType").dicData =
        res.data.data;
    });
    gainUser().then(res => {
      this.findObject(this.option.column, "createUser").dicData = res.data.data;
    })
    feeList().then(res => {
      this.feesOption = res.data.data.records
    })
    let i = 0;
    this.option.column.forEach(item => {
      if (item.search) i++
    })
    if (i % 3 !== 0) {
      const num = 3 - Number(i % 3)
      this.option.searchMenuSpan = num * 8;
      this.option.searchMenuPosition = "right";
    }
    this.option.column.forEach(item => {
      if (item.pickerOptions) {
        item.pickerOptions = {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
      }
    })
  },
  activated() {
    if (this.$route.query.check) {
      this.isShow = true
      // this.beforeOpenPage({id: this.$route.query.check.billId})
      this.detailData = {
        id: this.$route.query.check.billId,
        check: this.$route.query.check,
      };
      this.isShow = false;
      this.$store.commit("DOMCG_IN_DETAIL");
    }
    if (this.$route.query.id){
      this.isShow = true;
      this.beforeOpenPage({ id: this.$route.query.id });
    }
    if (this.$route.query.params) {
      this.beforeOpenPage({ id: this.$route.query.params })
    }
  },
  methods: {
    cellStyle() {
      return "padding:0;height:40px;";
    },
    searchCriteriaSwitch(type) {
      if (type) {
        this.option.height = this.option.height - 90
      } else {
        this.option.height = this.option.height + 90
      }
      this.$refs.crud.getTableHeight()
    },
    //删除列表后面的删除按钮触发触发(row, index, done)
    rowDel(row, index, done) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return deleteDetails(row.id);
      }).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.page.currentPage = 1;
        this.onLoad(this.page, { parentId: 0 });
      });
    },
    //查询全部
    initData() {
      customerList().then(res => {
        const column = this.findObject(this.option.column, "parentId");
        column.dicData = res.data.data.records;
      });
    },
    //新增子项触发
    handleAdd(row) {
      this.parentId = row.id;
      const column = this.findObject(this.option.column, "parentId");
      column.value = row.id;
      column.addDisabled = true;
      this.$refs.crud.rowAdd();
    },
    //查看跳转页面
    beforeOpenPage(row, index) {
      const data = {
        moduleName: 'cg',
        tableName: 'business_order',
        billId: row.id,
        no: localStorage.getItem('browserID')
      }
      this.checkLock(data).then(res => {
        if (res.data.code == 200) {
          this.detailData = {
            seeDisabled: true,
            id: row.id,
          };
          this.isShow = false;
          this.$store.commit("DOMCG_IN_DETAIL");
        }
      }).catch(err => {
        this.detailData = {
          id: row.id,
          seeDisabled: true,
          opDisabled: true
        };
        this.isShow = false;
        this.$store.commit("DOMCG_IN_DETAIL");
      })
    },
    //新增跳转页面
    beforeOpen(row, index) {
      this.detailData = {
        id: row.id,
      };
      this.isShow = false;
      this.$store.commit("DOMCG_IN_DETAIL");
    },
    editOpen(row, index) {
      const data = {
        moduleName: 'cg',
        tableName: 'business_order',
        billId: row.id,
        no: localStorage.getItem('browserID')
      }
      this.checkLock(data).then(res => {
        if (res.data.code == 200) {
          this.detailData = {
            seeDisabled: true,
            id: row.id,
          };
          this.isShow = false;
          this.$store.commit("DOMCG_IN_DETAIL");
        }
      }).catch(err => {
        this.detailData = {
          id: row.id,
          seeDisabled: true,
          opDisabled: true
        };
        this.isShow = false;
        this.$store.commit("DOMCG_IN_DETAIL");
      })
    },
    // 复制新单
    copyOrder() {
      const id = this.selection[0].id;
      this.detailData = {
        copyId: id,
      };
      this.isShow = false;
      this.$store.commit("DOMCG_IN_DETAIL");
    },
    //导出
    outExport() {
      this.$confirm('是否导出数据明细？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let queryParams = JSON.parse(JSON.stringify(this.search))
        if (queryParams.requiredArrivalDate) {
          this.$set(queryParams, 'requiredArrivalStartDate', queryParams.requiredArrivalDate[0] + " " + "00:00:00")
          this.$set(queryParams, 'requiredArrivalEndDate', queryParams.requiredArrivalDate[1] + " " + "23:59:59")
          delete queryParams.requiredArrivalDate
        }else {
          delete queryParams.requiredArrivalDate
          delete queryParams.requiredArrivalStartDate
          delete queryParams.requiredArrivalEndDate
        }
        if (queryParams.createTime.length>1) {
          queryParams.createStartTime = queryParams.createTime[0] + " " + "00:00:00"
          queryParams.createEndTime = queryParams.createTime[1] + " " + "23:59:59"
          delete queryParams.createTime
        }else {
          delete queryParams.createTime
          delete queryParams.createStartTime
          delete queryParams.createEndTime
        }
        const routeData = this.$router.resolve({
          path: '/api/trade-purchase/purchase-order/selOrderExport',      //跳转目标窗口的地址
          query: {
            ...queryParams    //括号内是要传递给新窗口的参数
          }
        })
        window.open(routeData.href.slice(1,routeData.href.length)+'&'+`${this.website.tokenHeader}=${getToken()}`);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消' //
        });
      })
    },
    //点击新增时触发
    beforeClose(done) {
      this.parentId = "";
      const column = this.findObject(this.option.column, "parentId");
      column.value = "";
      column.addDisabled = false;
      done();
    },
    //点击搜索按钮触发
    searchChange(params, done) {
      if (params.requiredArrivalDate) {
        this.$set(params, 'requiredArrivalStartDate', params.requiredArrivalDate[0] + " " + "00:00:00")
        this.$set(params, 'requiredArrivalEndDate', params.requiredArrivalDate[1] + " " + "23:59:59")
        this.$delete(params, 'requiredArrivalDate')
      }
      if (params.createTime) {
        params.createStartTime = params.createTime[0] + " " + "00:00:00"
        params.createEndTime = params.createTime[1] + " " + "23:59:59"
        this.$delete(params, 'createTime')
      }
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done()
    },
    searchReset() {
    },
    selectionChange(list) {
      this.selection = []
      this.selection = list;
      this.single = list.length !== 1;
      this.multiple = list.length == 0
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.page.currentPage = 1;
      this.onLoad(this.page, this.search);
    },
    onLoad(page, params) {
      let data = this.gobackSearch(params)
      let queryParams = Object.assign({ tradeType: 'GN' }, data, {
        size: page.pageSize,
        current: page.currentPage,
        // billType:'CG',
        // corpsTypeId: this.treeDeptId
      })
      this.loading = true;
      customerList(queryParams).then(res => {
        this.dataList = res.data.data.records
        this.page.total = res.data.data.total
        this.option.height = window.innerHeight - 240;
      }).finally(() => {
        this.loading = false;
      })
    },
    //树桩列点击展开触发
    treeLoad(tree, treeNode, resolve) {
      const parentId = tree.id;
      customerList({ parentId: parentId }).then(res => {
        resolve(res.data.data.records);
      });
    },
    goBack() {
      this.selection = []
      this.applyPaymentList = []
      this.single = true
      this.multiple = true
      this.detailData = this.$options.data().detailData
      this.isShow = true;
      this.onLoad(this.page, this.search);
    },
    gobackSearch(params) {
      params = Object.assign({}, this.search)
      if (params.requiredArrivalDate && params.requiredArrivalDate != '') {
        params.requiredArrivalStartDate = params.requiredArrivalDate[0] + " " + "00:00:00"
        params.requiredArrivalEndDate = params.requiredArrivalDate[1] + " " + "23:59:59"
        this.$delete(params, 'requiredArrivalDate')
      }
      if (params.createTime && params.createTime != '') {
        params.createStartTime = params.createTime[0] + " " + "00:00:00"
        params.createEndTime = params.createTime[1] + " " + "23:59:59"
        this.$delete(params, 'createTime')
      }
      return params
    },
    //列保存触发
    async saveColumn() {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(
        this.getColumnName(17),
        this.option
      );
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
        this.$nextTick(() => {
          this.$refs.crud.doLayout()
        })
      }
    },
    async resetColumn() {
      this.option = option;
      const inSave = await this.delColumnData(
        this.getColumnName(17),
        option
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout()
        })
        this.$message.success("重置成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    // 申请货款
    async applyPayment() {
      this.applyPaymentList = []
      if (this.selection.length > 1) {
        for (let item in this.selection) {
          if (this.selection[0].corpId !== this.selection[item].corpId) {
            return this.$message.error('批量结算供应商必须一致')
          }
        }
      }
      // let forData = await this.forData()
      // if (forData) {
      //   return this.$message.error('订单号:' + forData + '货款余额不足')
      // }
      let a = []
      this.selection.forEach(item => {
        item.itemsList = item.itemsList ? item.itemsList : [];
        let amount = Number(item.debitAmount) - Number(item.settlmentAmount);
        let quantity = 0;
        item.itemsList.map(e => {
          if (e.submitPay != 1) {
            // amount += Number(e.amount)
            quantity += Number(e.orderQuantity)
          }
        })
        const price = quantity === 0 ? 0 : Number(amount) / Number(quantity)
        let form = {
          belongCompany: item.belongCompany,
          srcOrderno: item.orderNo,
          itemType: "采购",
          corpsName: [{ cname: item.strCorpName, id: item.id }],
          corpId: item.corpId,
          srcParentId: item.id,
          currency: 'CNY',
          exchangeRate: '1',
          taxRate: '0',
          accDate: item.businesDate,
          srcType: 1,
          tradeType: 'GN',
          optionType: 'GN',
          costType: this.feesOption.find(e => e.cname == '货款') ? this.feesOption.find(e => e.cname == '货款').id : null,
          amount,
          quantity,
          price,
          unit: '条',
          remarks: item.orderRemark,
          itemorderAmount: item.orderAmount,
          itemId: item.id
        }
        a.push(form)
        // item.itemsList.forEach(e => {
        //   let form = {
        //     srcOrderno:item.orderNo,
        //     itemType:"采购",
        //     optionType:"GN",
        //     corpsName: [{cname: item.strCorpName, id: item.id}],
        //     corpId:item.corpId,
        //     srcParentId: item.id,
        //     currency: 'CNY',
        //     exchangeRate: '1',
        //     taxRate: '0',
        //     accDate: item.businesDate,
        //     srcType: 1,
        //     tradeType: 'GN',
        //     costType: this.feesOption.find(e => e.cname == '货款')? this.feesOption.find(e => e.cname == '货款').id: null,
        //     goodName: e.goodsName,
        //     price: e.price,
        //     quantity: e.orderQuantity,
        //     unit: e.unit,
        //     amount: e.amount,
        //   }
        //   a.push(form)
        // })
      })
      this.applyPaymentList = [...a]
      // this.beforeBillData(true);
      this.financialAccountDialog = true;
    },
    async forData() {
      for (let item in this.selection) {
        let res = await getApplyAmount({ srcBillId: this.selection[item].id, billType: "申请" })
        if (this.selection[item].orderAmount <= res.data.data) {
          return this.selection[item].orderNo
        }
      }
    },
    beforeBillData(type) {
      if (type) { //申请货款
        // this.billData.srcId = -1
      }
    },
    //关闭账单
    choceFun() {
      this.financialAccountDialog = false
    },
    feeSubmit() {
      this.onLoad(this.page, this.search)
    },
    // 生成工厂发货
    createPlant(row, index) {
      let ids = [];
      row.itemsList.forEach(item => {
        ids.push(item.id)
      })
      let data = {
        id: row.id,
        orderItemIds: ids
      }
      generateShipment(data).then(res => {
        let generateShipmentId = res.data.data.id
        let generateMount = res.data.data.orderAmount
        this.$confirm("此操作将生成工厂发货，是否继续?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true
          res.data.data.orgId = res.data.data.id
          res.data.data.srcId = res.data.data.srcId
          res.data.data.deliveryStatus = '录入'
          res.data.data.salesCompany = res.data.data.belongToCorpId
          res.data.data.totalWeight = res.data.data.cartonWeight
          res.data.data.totalVolumn = res.data.data.cntrVolumn
          res.data.data.deliveryAmount = 0
          res.data.data.totalQuantity = 0
          res.data.data.purchaseAmount = 0
          res.data.data.orderItemsList.forEach(item => {
            item.containerVolume = item.cntrVolumn
            item.actualWeight = item.cartonWeight
            item.specificationAndModel = item.itemType
            item.orgOrderNo = res.data.data.orgOrderNo
            item.inventoryNumber = item.storageQuantity
            item.srcId = item.id
            item.purchaseAmount = item.purchaseAmount
            item.purchaseQuantity = Number(item.orderQuantity)
            item.actualQuantity = (Number(item.orderQuantity) - Number(item.actualQuantity))
            res.data.data.deliveryAmount = Number(res.data.data.deliveryAmount) + Number(item.deliveryAmount)
            res.data.data.totalQuantity = Number(res.data.data.totalQuantity) + Number(item.actualQuantity)
            res.data.data.purchaseAmount = Number(res.data.data.purchaseAmount) + Number(item.deliveryAmount)
            res.data.data.deliveryAmount = Number(res.data.data.deliveryAmount ? res.data.data.deliveryAmount : 0).toFixed(2)
            res.data.data.purchaseAmount = Number(res.data.data.purchaseAmount ? res.data.data.purchaseAmount : 0).toFixed(2)
            delete item.id
            delete item.pid
          })
          res.data.data.deliveryItemsList = res.data.data.orderItemsList
          res.data.data.businessDate = getCurrentDate()
          delete res.data.data.createTime
          delete res.data.data.id
          delete res.data.data.sysNo
          delete res.data.data.orderItemsList
          delete res.data.data.corpName
          delete res.data.data.belongToCorpList
          res.data.data.deliveryAmount = res.data.data.debitAmount
          res.data.data.srcOrderNo = res.data.data.orgOrderNo
          delete res.data.data.debitAmount
          res.data.data.deliveryItemsList.forEach(item => {
              item.deliveryAmount = item.amount
          })
          // res.data.data.srcId = generateShipmentId
          res.data.data.purchaseAmount = generateMount
          genfactory(res.data.data).then(() => {
            this.$message.success('生成工厂发货成功')
            this.onLoad(this.page, this.search);
          })
        });
        // this.$router.$avueRouter.closeTag("/businessManagement/receipt/index");
        // this.$router.push({
        //   path: "/businessManagement/receipt/index",
        //   query: { form: JSON.stringify(res.data.data) },
        // });
      })
    },
  }
}
</script>

<style scoped>
</style>
