<template>
  <div>
    <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(0)">返回列表
        </el-button>
      </div>
      <div class="add-customer-btn">
        <el-button class="el-button&#45;&#45;small-yh" style="margin-right: 10px" type="primary" size="small"
          v-if="!editButton" @click="confirmEditing">编辑
        </el-button>
        <el-button class="el-button--small-yh" type="primary" size="small"
          :disabled="form.financeStatus == '已收款' || isSaveBtn" @click="editCustomer">保存数据
        </el-button>
        <el-button class="el-button--small-yh" type="warning" :disabled="isFinanceBtn" size="small" @click="collection">{{
          form.financeStatus ==
          '已收款' ? '撤销收款' : '收款' }}
        </el-button>
        <!-- <el-button class="el-button--small-yh" type="primary" size="small" v-if="form.id">启用
        </el-button> -->
      </div>
    </div>
    <div style="margin-top: 50px">
      <trade-card title="基础信息">
        <avue-form :option="optionForm" v-model="form" ref="form">
            <template slot-scope="scope" slot="corpId">
                <el-select v-model="form.corpId" placeholder="请选择">
                    <el-option
                        v-for="item in corpIdData"
                        :key="item.id"
                        :label="item.cname"
                        :value="item.id">
                    </el-option>
                </el-select>
            </template>
            <!--<template slot-scope="scope" slot="settlementDate">-->
            <!--    <el-date-picker-->
            <!--        v-model="value1"-->
            <!--        type="date"-->
            <!--        format="yyyy-MM-dd",-->
            <!--        placeholder="选择日期">-->
            <!--    </el-date-picker>-->
            <!--</template>-->
        </avue-form>
      </trade-card>
      <trade-card title="明细信息">
        <avue-crud :option="optionContacts" v-model="formContacts" ref="formContacts" :data="form.settlementItemsList"
          @row-save="rowSave" @row-update="rowUpdate"
          @resetColumn="resetColumnTwo('formContacts', 'optionContacts', 'optionContactsBack', 267.1)"
          @saveColumn="saveColumnTwo('formContacts', 'optionContacts', 'optionContactsBack', 267.1)">
          <template slot-scope="scope" slot="menuLeft">
            <el-button type="primary" icon="el-icon-plus" :disabled="form.financeStatus == '已收款' || isMenu" size="small"
              @click="rowAdd()">选择订单</el-button>
          </template>
          <template slot-scope="{ row, index }" slot="contractNumber">
            <span style="color: #409EFF;cursor: pointer" @click.stop="viewDocuments(row)">{{ row.contractNumber }}
            </span>
          </template>
          <template slot-scope="{type,size,row,index,disabled}" slot="menu">
            <el-button :size="size" :disabled="form.financeStatus == '已收款' || isMenu" :type="type"
              :icon="row.$cellEdit ? 'el-icon-plus' : 'el-icon-edit'" @click="$refs.formContacts.rowCell(row, index)">{{
                row.$cellEdit ? '确认' : '修改' }}
            </el-button>
            <el-button icon="el-icon-delete" :size="size" :disabled="form.financeStatus == '已收款' || isMenu" :type="type"
              @click="rowDelBox(row, index)">删除
            </el-button>
          </template>
        </avue-crud>
      </trade-card>

        <containerTitle title="上传附件"></containerTitle>
        <c-upload v-loading="loadingBtn" typeUpload="LT"
                  deleteUrl="/api/trade-purchase/woodHarvestingCloud/removeByFileId" :data="filesList" display
                  :enumerationValue="35.1"></c-upload>
    </div>
    <el-dialog title="导入订单" v-if="billDetailDialog" append-to-body class="el-dialogDeep" :visible.sync="billDetailDialog"
      width="80%" :close-on-click-modal="false" :destroy-on-close="true" :close-on-press-escape="false" top="10vh"
      v-dialog-drag>
      <bill-detail :params="params" :billType="billType" :flag="1" @closeFun="closeBillDetail"
        @importProMent="importProMent">
      </bill-detail>
    </el-dialog>
  </div>
</template>

<script>
import billDetail from "@/components/bill/selectOrderDetailList";
import { saveSubmit, collectionAndPayment, revokeCollectionAndPayment, detail, removeItems, remove } from '@/api/accountingManagement/index.js';
import { getList } from "@/api/collectionSettlement/index.js";
import {skgetKh} from "@/api/tirePartsMall/salesManagement/saleOrder";


export default {
  name: "detailsPage",
  components: {
    billDetail
  },
  data() {
    return {
        // 上传附件的需要参数
        loadingBtn:false,
        filesList:[],

        corpIdData:[],

      disabled: false,
      editButton: false,
      isSaveBtn: false,
      isFinanceBtn: false,
      isMenu: false,
      billDetailDialog: false,
      params: {},
      form: {
        settlementItemsList: []
      },
      optionForm: {
        disabled: false,
        menuBtn: false,
        span: 8,
        column: [{
          label: '客户',
          prop: "corpId",
          type: 'select',
          remote: true,
          props: {
            label: 'cname',
            value: 'id'
          },
          dicUrl: '/api/blade-sales-part/corpsDesc/listAll?cname={{key}}&corpType=KH&enableOrNot=1',
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '收款账户',
          prop: "accountName",
          remote: true,
          type: 'select',
          props: {
            label: 'cname',
            value: 'id',
            res: 'data.records'
          },
          click: () => {
            this.$refs.form.dicInit()
          },
          dicUrl: '/api/blade-sales-part/accountManagement/list?enableOrNot=1&cname={{key}}&billType=HYCK',
          // change: (data => {
          //   console.log(data);
          //   console.log(this.$refs.form.DIC.accountName);
          //   if(this.$refs.form.DIC.accountName){
          //     const targetObject = this.$refs.form.DIC.accountName.find(obj => obj.cname == data.value);
          //     this.form.accountId = targetObject.id
          //   }
          // }),
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '金额',
          prop: "amount",
          disabled: true,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: "经办人",
          prop: "handledByName",
          type: "select",
          props: {
            label: "name",
            value: "name"
          },
          dicUrl: "/api/blade-user/financeList",
          filterable: true,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }],
          value: '青岛'
        }, {
          label: '收款日期',
          prop: "settlementDate",
          type: "date",
          overHidden: true,
          width: 100,
          searchRange: true,
          searchDefaultTime: ["00:00:00", "23:59:59"],
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
          value: ''
        }, {
          label: '单据编号',
          prop: "sysNo",
          disabled: true
        }, {
          label: '备注',
          prop: "remarks",
          type: 'textarea',
          span: 24,
          minRows: 2
        }]
      },
      formContacts: {},
      optionContacts: {},
      optionContactsBack: {
        disabled: false,
        align: 'center',
        index: true,
        // addBtnText: "录入明细",
        refreshBtn: false,
        dialogDrag: true,
        addBtn: false,
        span: 8,
        height: 600,
        // addRowBtn: true,
        editBtn: false,
        delBtn: false,
        menuWidth: 140,
        dialogTop: 25,
        dialogWidth: "80%",
        column: [
          //   {
          //   label: '单据编号',
          //   prop: 'attn',
          //   cell: true
          // },
          {
            label: '合同号',
            prop: 'contractNumber',
            cell: false
          }, {
            label: '应收金额',
            prop: 'accountsAmount',
            cell: false
          }, {
            label: '结算金额',
            prop: 'settlmentAmount',
            cell: false,
            decimals: 2
          }, {
            label: '本次金额',
            prop: 'thisAmount',
            cell: true
          }, {
            label: '来源主表id',
            hide: true,
            showColumn: false,
            prop: 'srcParentId',
            cell: true
          }, {
            label: '来源单据编号',
            prop: 'srcBillNo',
            hide: true,
            showColumn: false,
            cell: false
          }, {
            label: '所属公司id',
            prop: 'salesCompanyId',
            hide: true,
            showColumn: false,
            cell: false
          }, {
            label: '所属公司名称',
            prop: 'salesCompanyName',
            hide: true,
            showColumn: false,
            cell: false
          }, {
            label: '业务日期',
            prop: "businesDate",
            disabled: false,
            type: "datetime",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ]
          }, {
            label: '备注',
            prop: 'remarks',
            cell: true
          }]
      }
    }
  },
  props: {
    onLoad: Object,
    detailData: Object
  },
  async created() {

    //  获取今天的日期
    var today = new Date();
    var year = today.getFullYear();
    var month = String(today.getMonth() + 1).padStart(2, '0');
    var day = String(today.getDate()).padStart(2, '0');
    var hours = String(today.getHours()).padStart(2, '0');
    var minutes = String(today.getMinutes()).padStart(2, '0');
    var seconds = String(today.getSeconds()).padStart(2, '0');

    // 构建今天的日期时间字符串
    var todayDateTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    if (this.onLoad.id) {
      this.refresh(this.onLoad.id)
      this.$set(this.optionForm, 'disabled', true)
      this.$set(this.optionContactsBack, 'disabled', true)
      this.isSaveBtn = true
      this.isFinanceBtn = true

      this.isMenu = true
    } else {
      this.isFinanceBtn = true
      this.findObject(this.optionForm.column, 'settlementDate').value = todayDateTime
      this.editButton = true
      // console.log(this.form.settlementDate = '2023-07-03');
    }

    // 先处理时间在赋值哦 防止数据渲染不上页面
      let thisAmountSum = 0
      this.optionContacts = await this.getColumnData(this.getColumnName(267.1), this.optionContactsBack);
      this.findObject(this.optionContacts.column, "thisAmount").change = ({ value, column }) => {
          thisAmountSum = 0
          for (let item of this.form.settlementItemsList) {
              thisAmountSum += item.thisAmount;
          }
          this.form.amount = Number(thisAmountSum)
      }

    // 获取客户的数据
      skgetKh().then(res=>{
        console.log(res,330)
          this.corpIdData = res.data.data
    })
    // this.corpIdData
  },
  methods: {
    rowDelBox(row, index) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id) {
          console.log(this.form);
          removeItems({ ids: row.id }).then(res => {
            this.form.settlementItemsList.splice(index, 1);
            this.$message.success("操作成功!");
          });
        } else {
          this.form.settlementItemsList.splice(index, 1);
          this.$message.success("操作成功!");
        }
      }
      )
        ;
    },
    rowSave(form, done, loading) {
      done(form)
    },
    rowUpdate(form, index, done, loading) {
      done(form)
    },
    refresh(id, type) {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(255,255,255,0.7)'
      })
      detail({ id: id }).then(res => {
        this.form = res.data.data
          this.filesList = res.data.data.filesList
        // if (res.data.data.financeStatus == '已收款') {
        //   console.log('已收款');
        //   this.$set(this.optionForm, 'disabled', true)
        //   this.$set(this.optionContactsBack, 'disabled', true)
        // } else {
        //   this.$set(this.optionForm, 'disabled', false)
        // }

        loading.close();
      }).catch(() => {
        loading.close();
      })
    },
    //新增
    rowAdd() {
      if (!this.form.corpId) {
        this.$message.warning("请先选择客户!")
        return
      }
      this.params = {
        customerId: this.form.corpId,
        generateTask: '已生成',
        bsType: 'XS',
        actualPaymentStatus: '2'
      }
      this.billDetailDialog = true;

      // this.$refs.formContacts.rowAdd()
    },
    //导入
    importProMent(list) {
      console.log(list);
      // return
      // for (let item of this.dataList){
      //   for (let li of list){
      //     if (item.srcSysno == li.srcSysno && item.srcRefno == li.srcRefno && new Date(item.rentEndDate) == new Date(li.rentEndDate)){
      //       return this.$message.error(`合同号${item.accSysNo}已存在`)
      //     }
      //   }
      // }
      list.forEach((item, index) => {
        item.contractNumber = item.ordNo;
        item.accountsAmount = item.totalMoney
        item.settlmentAmount = item.paymentAmountTl
        item.thisAmount = (Number(item.totalMoney) - Number(item.paymentAmountTl))
        item.srcParentId = item.id
        item.srcBillNo = item.ordNo
        item.salesCompanyId = item.salesCompanyId
        item.salesCompanyName = item.salesCompanyName
        item.id = null
        delete item.ordNo;
        this.$refs.formContacts.rowCellAdd(item);
      })
      //明细列表所有合同号 去重 加， 为主表合同号
      // this.$set(this.form,'srcOrderno',Array.from(new Set(this.dataList.map(item =>{ return item.srcOrderno}))).join(','))

      this.billDetailDialog = false;
    },
    //保存数据
    editCustomer() {
      this.$refs["form"].validate((valid, done) => {
        done()
        if (valid) {
          let data = {
            ...this.form,
            dc: 'd',
            billType: 'SK',
            corpName: this.form.$corpId,
              filesList:this.filesList
          }
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(255,255,255,0.7)'
          });
          saveSubmit(data).then(res => {
            console.log(res);
            this.isFinanceBtn = false
            this.refresh(res.data.data.id)
            this.$message.success('保存成功')
            loading.close();
          }).catch(() => {
            loading.close()
          })
        }
      })

    },
    //收款
    collection() {
      this.$refs["form"].validate((valid, done) => {
        done()
        if (valid) {
          if (this.form.financeStatus !== '已收款') {
            console.log('this.form.financeStatus', this.form.financeStatus);
            this.$confirm("确认收款?", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              const loading = this.$loading({
                lock: true,
                text: '加载中',
                spinner: 'el-icon-loading',
                background: 'rgba(255,255,255,0.7)'
              });
              let data = {
                ...this.form,
                dc: 'd',
                billType: 'SK',
                corpName: this.form.$corpId
              }
              saveSubmit(data).then(res => {
                collectionAndPayment(data).then((res => {
                  this.refresh(res.data.data.id)
                  this.$set(this.optionForm, 'disabled', true)
                  this.$set(this.optionContactsBack, 'disabled', true)
                  this.$message.success('收款成功')
                  loading.close()
                }))
              }).catch(() => {
                loading.close()
              })
            })
          } else {
            this.$confirm("确认撤销退款?", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              const loading = this.$loading({
                lock: true,
                text: '加载中',
                spinner: 'el-icon-loading',
                background: 'rgba(255,255,255,0.7)'
              });
              let data = {
                ...this.form,
                dc: 'd',
                billType: 'SK'
              }
              revokeCollectionAndPayment(data).then((res => {
                this.refresh(res.data.data.id)
                this.editButton = false
                this.$message.success('撤销收款成功')
                loading.close()
              }))
            })
          }
        }
      })

    },
    confirmEditing() {
      this.editButton = true
      if (this.form.financeStatus == '已收款') {
        this.$set(this.optionForm, 'disabled', true)
        this.$set(this.optionContactsBack, 'disabled', true)
        this.isFinanceBtn = false
      } else {
        this.$set(this.optionForm, 'disabled', false)
        this.$set(this.optionContactsBack, 'disabled', false)
        this.isFinanceBtn = false
        this.isSaveBtn = false
        this.isMenu = false
      }
    },
    //查看单据
    viewDocuments(row) {
      console.log(row);
      this.$router.$avueRouter.closeTag('/tirePartsMall/salesManagement/saleOrder/index');
      this.$router.push({
        path: "/tirePartsMall/salesManagement/saleOrder/index",
        query: { detail: row, type: 'S' },
      });
    },
    //关闭
    closeBillDetail() {
      this.billDetailDialog = false;
    },
    //自定义列保存
    async saveColumnTwo(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    backToList(type) {
      this.$emit("backToList", type);
    }
  }
}
</script>

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