<template>
  <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>
      <el-button
        class="el-button--small-yh add-customer-btn"
        type="primary"
        :disabled="disabled"
        @click="editCustomer"
      >{{form.id?'确认修改':'确认新增'}}
      </el-button>
    </div>
    <div style="margin-top: 60px">
      <el-form :model="form" ref="form" label-width="130px">
        <containerTitle title="基础信息"></containerTitle>
        <basic-container style="margin-bottom: 10px">
          <el-row>
            <el-col v-for="(item, index) in basicData.column" :span="item.span?item.span:8" :key="index">
              <el-form-item :label="item.label" :prop="item.prop" :rules="item.rules">
                <el-date-picker v-if="item.type === 'datetime'" style="width: 100%;" v-model="form[item.prop]" size="small" type="datetime" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss"/>
                <el-select v-else-if="item.type === 'select'" style="width: 100%" v-model="form[item.prop]" size="small" placeholder="请选择" clearable filterable>
                  <el-option
                    v-for="(data, index) in item.dicData"
                    :key="index"
                    :label="data.label"
                    :value="data.value"
                  ></el-option>
                </el-select>
                <el-input type="textarea" v-else-if="(item.prop === 'orderRemark')" v-model="form[item.prop]"   size="small" autocomplete="off" placeholder="请输入"></el-input>
                <el-input type="age" v-else v-model="form[item.prop]" size="small" autocomplete="off" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </basic-container>
<!--        商品明细-->
        <containerTitle title="商品明细"></containerTitle>
        <basic-container style="margin-bottom: 10px">
          <avue-crud
            :option="importInventory"
            v-model="importInventoryForm"
            :data="importInventoryData"
            ref="importInventory"
            @row-save="rowSaveList"
            @row-update="rowUpdateList"
            @row-del="rowDelList"
            @selection-change="productSelection"
          >
            <template slot="menuLeft" slot-scope="{size}">
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="small"
                         @click="newDetails"
              >录入明细</el-button>
              <el-button type="primary"
                         size="small"
                         :disabled="selection.length < 1"
                         @click="generateShipmentD"
              >生成发货单
              </el-button>
              <el-button type="info"
                         size="small"
              >收款记录
              </el-button>
            </template>
            <template slot-scope="{row,index}" slot="menu">
              <el-button
                type="text"
                size="small"
                @click="rowCell(row,index)"
              >{{ row.$cellEdit ? '保存' : '修改' }}
              </el-button>
              <el-button
                type="text"
                size="small"
                v-if="!row.$cellEdit"
                @click="sendHandle"
              >发货</el-button>
            </template>
          </avue-crud>
        </basic-container>
<!--        其他费用-->
        <containerTitle title="其他费用"></containerTitle>
        <basic-container style="margin-bottom: 40px">
          <avue-crud
            :option="advantageProject"
            v-model="advantageProjectForm"
            :data="advantageProjectData"
            ref="crudProject"
            @row-save="rowSaveProject"
            @row-update="rowUpdateProject"
            @row-del="rowDelProject"
          >
            <template slot="code" slot-scope="{row,index}">
              <span style="float: left;padding-top: 2px">{{row.code}}</span><el-button type="text" size="mini" style="float: right" @click="choice(row)">选择</el-button>
            </template>
            <template slot-scope="{row,index}" slot="menu">
              <el-button
                type="text"
                size="small"
                @click="rowCellTwo(row,index)"
              >{{row.$cellEdit?'保存':'修改'}}</el-button>
            </template>
            <template slot="menuLeft" slot-scope="{size}">
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="small"
                         @click="costIncrease"
              >录入明细</el-button>
            </template>
          </avue-crud>
        </basic-container>
        <!--        合同上传-->
        <containerTitle title="合同附件"></containerTitle>
        <basic-container style="margin-bottom: 40px">
          <avue-crud
            :option="uploadList"
            v-model="bankOfDepositForm"
            :data="bankOfDepositData"
            @row-save="rowSaveBankOfDeposit"
            @row-update="rowUpdateBankOfDeposit"
            @row-del="rowDelBankOfDeposit"
          ></avue-crud>
        </basic-container>
      </el-form>
    </div>


    <el-dialog
      title="导入商品"
      append-to-body
      class="el-dialogDeep"
      :visible.sync="dialogVisible"
      width="80%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false">
      <el-row style="height: 0;">
        <el-col :span="5">
          <div>
            <el-scrollbar>
              <basic-container>
                <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick"/>
              </basic-container>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19">
          <basic-container>
            <avue-crud :option="optionTwo"
                       :table-loading="loading"
                       :data="data"
                       ref="crud"
                       @refresh-change="refreshChange"
                       @selection-change="selectionChange"
                       :page.sync="page"
                       @on-load="onLoad">

            </avue-crud>
          </basic-container>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="importGoods" v-if="commodityData !== true">导入</el-button>
          <el-button type="primary" @click="importChoice" v-if="commodityData === true"
                     :disabled="tableData.length !== 1">导入</el-button>
        </span>
    </el-dialog>
<!--    导入其他费用-->
    <el-dialog
      title="导入费用"
      append-to-body
      class="el-dialogDeep"
      :visible.sync="dialogCost"
      width="80%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false">
      <el-row style="height: 0;">
        <el-col :span="5">
          <div>
            <el-scrollbar>
              <basic-container>
                <avue-tree :option="treeOptionCost" :data="treeData" @node-click="nodeClickCost"/>
              </basic-container>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19">
          <basic-container>
            <avue-crud :option="optionTwoCost"
                       :table-loading="loadingCost"
                       :data="dataCost"
                       ref="crud"
                       @refresh-change="refreshChangeCost"
                       @selection-change="selectionChangeCost"
                       :page.sync="pageCost"
                       @on-load="onLoadCost">
            </avue-crud>
          </basic-container>
        </el-col>
      </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogCost = false">取 消</el-button>
          <el-button type="primary" @click="importCost" v-if="choiceData !== true">导入</el-button>
          <el-button type="primary" @click="choiceCost" v-if="choiceData === true" :disabled="tableDataCost.length !== 1">导入</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import importInventory from './config/importInventory.json';
import uploadList from './config/uploadList.json';
import advantageProject from "./config/advantageProject.json";
import optionTwoCost from "./config/mainListCost.json";
import {getDeptLazyTree,getDeptLazyTreeTwo, customerList} from "@/api/basicData/basicFeesDesc";
import commodity from "./config/commodity.json"
import {
  typeSave, detail, deleteDetails,
  corpstypeTree,
  corpsattn,
  corpsbank,
  corpsfiles,
  corpsitem,
  getList,
  detailList
} from "@/api/basicData/configuration"
import {detailSaleList,
  submitData,
  goodsListRemove,
  feesListRemove,
  updateListRemove,
  generateShipment} from "@/api/importTrade/salesContract"

export default {
  name: "detailsPage",
  data() {
    return {
      disabled: false,
      dialogCommodity: false,
      dialogVisible: false,
      form: {},
      //  基础信息
      basicData: {
        column: [
          {
            label: '系统号',
            prop: 'sysNo',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '订单号',
            prop: 'orderNo',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '订单日期',
            prop: 'businesDate',
            type:'datetime',
            data: [],
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '业务员',
            prop: 'salesName',
            // type:'select',
            dicData: [],
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '销售公司',
            prop: 'belongToCorpId',
            // type:'select',
            dicData: [],
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '工厂/贸易商名称',
            prop: 'corpId',
            // type:'select',
            dicData: [],
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },  {
            label: '发票号（PI）',
            prop: 'proformInvoice',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '合同金额',
            prop: 'orderAmount',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '收款金额',
            prop: 'settlmentAmount',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '起运港',
            prop: 'portOfLoad',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '目的港',
            prop: 'portOfDestination',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '包装要求',
            prop: 'packageRemarks',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '客户首付日期',
            prop: 'advanceCollectionDate',
            type: 'datetime',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '首付比例',
            prop: 'downPayment',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '首付金额',
            prop: 'advancePayment',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '计划交期',
            prop: 'plannedDeliveryDate',
            type: 'datetime',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '发票重量',
            prop: 'invoiceWeight',
            data: [],
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '码单重量',
            prop: 'billWeight',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '销售单价',
            prop: 'salesPrice',
            data: [],
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },  {
            label: '币别',
            prop: 'currency',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '汇率',
            prop: 'exchangeRate',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '提成标准',
            prop: 'commissionRate',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: "备注",
            span: 24,
            prop: "orderRemark",
            mock: {
              type: 'county'
            }
          }
        ],
      },
      // 导入库存配置
      importInventory: importInventory,
      importInventoryForm: {},
      importInventoryData: [],
      dialogStock: false,
      // 其他费用
      advantageProject: advantageProject,
      advantageProjectData: [],
      advantageProjectForm: {},
      dialogCost: false,
      choiceData: false,
      treeOptionCost:{
        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: {
          labelText: '标题',
          label: 'title',
          value: 'value',
          children: 'children'
        }
      },
      treeOption: {
        nodeKey: 'id',
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentId = (node.level === 0) ? 0 : node.data.id;
          getDeptLazyTreeTwo(parentId).then(res => {
            resolve(res.data.data.map(item => {
              return {
                ...item,
                leaf: !item.hasChildren
              }
            }))
          });
        },
        addBtn: false,
        menu: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'title',
          value: 'value',
          children: 'children'
        }
      },
      // 导入商品配置
      optionGoods: [],
      loadingGoods: false,
      dataGoods:[],
      pageGoods:{
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      // 导入其他费用配置
      optionTwoCost: optionTwoCost,
      loadingCost: false,
      dataCost:[],
      pageCost:{
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      tableDataCost: [],
      treeDeptId: '',
      treeDeptIdCost: '',
      choiceIndex: '',
      // 合同上传数据
      uploadList: uploadList,
      // 合同数据
      bankOfDepositData: [],
      bankOfDepositForm: {},

      optionTwo: commodity,
      loading: false,
      data: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      tableData: [],
      commodityData: false,
      selection: [],
    }
  },
  created() {
    if (this.$route.query.id) {
      let id = this.$route.query.id.replace(/\"/g, "")
      detailSaleList(id).then(res => {
        this.form = res.data.data;
        this.importInventoryData = this.form.orderItemsList
        this.advantageProjectData = this.form.orderFeesList
        this.bankOfDepositData = this.form.orderFilesList
      })
    }
  },
  methods: {
    editCustomer() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let submitDto = {
            orderItemsList: [],
            orderFeesList: [],
            orderFilesList: []
          };
          submitDto = Object.assign({}, submitDto, this.form)
          submitDto.orderItemsList = this.importInventoryData
          submitDto.orderFeesList = this.advantageProjectData
          submitDto.orderFilesList = this.bankOfDepositData
          submitData(submitDto).then(res => {
            console.log(res)
            this.backToList()
          })
        } else {
          return false;
        }
      });
    },
    //商品选中触发
    productSelection(selection){
      this.selection = selection
    },
    //生成发货单
    generateShipmentD(){
      let lsit = []
      for (let item in this.selection){
        if (!this.selection[item].id){
          return this.$confirm('商品信息有未保存数据, 是否立即保存?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.editCustomer()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }else {
          lsit.push(this.selection[item].id)
        }
      }
      let data = {
        id:this.form.id,
        orderItemIds: lsit
      }
      generateShipment(data).then(res=>{
        this.$router.push({
          path: "importInvoice_detailsPage",
          query: {form: JSON.stringify(res.data.data)},
        });
      })
    },
    //商品明细导入
    newDetails(){
      this.dialogVisible = !this.dialogVisible
    },
    //商品编辑
    rowCell(row, index) {
      console.log(row)
      // row.$cellEdit = !row.$cellEdit
      this.$refs.importInventory.rowCell(row, index)
    },
    //其他费用编辑
    rowCellTwo(row, index) {
      console.log(row)
      this.$refs.crudProject.rowCell(row, index)
    },
    //其他费用新增触发
    costIncrease(){
      this.dialogCost = !this.dialogCost
      this.choiceData = false
    },
    //费用查询
    onLoadCost(page, params = {}) {
      this.loadingCost = true;
      let queryParams = Object.assign({}, params, {pageSize: page.pageSize, pageNum: page.currentPage,parentId:0,feesTypeId:this.treeDeptIdCost})
      customerList(queryParams).then(res => {
        console.log(res)
        const data = res.data.data;
        this.pageCost.total = data.total;
        this.dataCost = data.records;
        this.loadingCost = false;
      });
    },
    //商品列表查询
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query), this.treeDeptId).then(res => {
        console.log(res)
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
    //点击费用明细选择触发
    choice(row){
      this.dialogCost = !this.dialogCost
      this.choiceData = true
      this.choiceIndex = row.$index
    },
    nodeClickCost(data){
      this.treeDeptIdCost = data.id;
      this.pageCost.currentPage = 1;
      this.onLoadCost(this.pageCost);
    },
    //刷新触发
    refreshChange() {
      this.treeDeptId = '';
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //选中触发
    selectionChange(list) {
      this.tableData = list
    },
    //费用刷新触发
    refreshChangeCost() {
      this.treeDeptIdCost = '';
      this.pageCost.currentPage = 1;
      this.onLoadCost(this.pageCost);
    },
    //确认导入触发
    importGoods() {
      if (this.tableData.length > 0) {
        for (let item in this.tableData) {
          console.log(this.tableData[item])
          this.tableData[item].priceCategory = this.tableData[item].goodsTypeName
          delete this.tableData[item].goodsTypeName
          this.tableData[item].itemId = this.tableData[item].id
          delete this.tableData[item].id
          this.$refs.importInventory.rowCellAdd(this.tableData[item]);
          this.$refs.importInventory.rowCell(this.tableData[item], this.importInventoryData.length - 1)
        }
      }
      this.tableData = []
      this.dialogVisible = false
    },
    //费用选中触发
    selectionChangeCost(list){
      this.tableDataCost = list
    },
    //导入页左商品类型查询
    nodeClick(data) {
      this.treeDeptId = data.id;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //费用导入触发
    importCost(){
      // this.advantageProjectForm = this.advantageProjectForm.concat(this.tableDataCost)
      if (this.tableDataCost.length>0){
        for(let item in this.tableDataCost){
          console.log(this.tableDataCost[item])
          this.tableDataCost[item].itemId = this.tableDataCost[item].id
          this.tableDataCost[item].feeName = this.tableDataCost[item].cname
          delete this.tableDataCost[item].id
          this.$refs.crudProject.rowCellAdd(this.tableDataCost[item]);
          this.$refs.crudProject.rowCell(this.tableDataCost[item], this.advantageProjectForm.length-1)
        }
      }
      this.tableDataCost = []
      this.dialogCost = false
    },
    //导入商品触发
    importChoice() {
      if (this.tableData.length === 1) {
        this.importInventoryData[this.choiceIndexT].cname = this.tableData[0].cname
        this.importInventoryData[this.choiceIndexT].code = this.tableData[0].code
        this.importInventoryData[this.choiceIndexT].typeno = this.tableData[0].typeno
        this.importInventoryData[this.choiceIndexT].specificationAndModel = this.tableData[0].specificationAndModel
        this.importInventoryData[this.choiceIndexT].itemId = this.tableData[0].id
        this.importInventoryData[this.choiceIndexT].priceCategory = this.tableData[0].goodsTypeName
      }
      this.dialogVisible = !this.dialogVisible
      this.commodityData = false
    },
    //费用编辑导入触发
    choiceCost(){
      if (this.tableDataCost.length === 1){
        this.advantageProjectData[this.choiceIndex].feeName = this.tableDataCost[0].cname
        this.advantageProjectData[this.choiceIndex].itemId = this.tableDataCost[0].id
        this.advantageProjectData[this.choiceIndex].code = this.tableDataCost[0].code
      }
      this.dialogCost = !this.dialogCost
      this.choiceData = false
    },
    //新增附件上传保存触发
    rowSaveBankOfDeposit(row, done, loading){
      this.bankOfDepositData.push(row)
      done()
    },
    //修改附件上传触发
    rowUpdateBankOfDeposit(row, index, done, loading) {
      done(row);
    },
    //删除附件上传触发
    rowDelBankOfDeposit(row, index, donerowDel) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id){
          updateListRemove(row.id).then(res=>{
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.bankOfDepositData.splice(index, 1);
          })
        }else {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.bankOfDepositData.splice(index, 1);
        }
      })
    },
    //新增明细保存触发
    rowSaveList(row, done, loading){
      // this.advantageProjectData.push(row)
      done()
    },
    //修改明细触发
    rowUpdateList(row, index, done, loading) {
      done(row);
    },
    //删除商品明细触发
    rowDelList(row, index, donerowDel) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id){
          goodsListRemove(row.id).then(res=>{
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.importInventoryData.splice(index, 1);
          })
        }else {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.importInventoryData.splice(index, 1);
        }
      })
    },
    //新增明细保存触发
    rowSaveProject(row, done, loading){
      // this.advantageProjectData.push(row)
      done()
    },
    //修改明细触发
    rowUpdateProject(row, index, done, loading) {
      done(row);
    },
    //删除明细触发
    rowDelProject(row, index, donerowDel) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id){
          feesListRemove(row.id).then(res=>{
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.advantageProjectData.splice(index, 1);
          })
        }else {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.advantageProjectData.splice(index, 1);
        }
      })
    },
    // 发货
    sendHandle() {
      this.$message.success('发货成功')
    },
    backToList() {
      this.$router.$avueRouter.closeTag();
      this.$router.push({
        path: '/salesManagement/salesContract/index',
        query: {}
      });
    },
  },
}
</script>

<style scoped lang="scss">
.customer-head {
  position: fixed;
  top: 105px;
  width: 100%;
  margin-left: -10px;
  height: 62px;
  background: #ffffff;
  box-shadow: 0 4px 12px 0px rgba(232, 232, 235, 1);
  z-index: 999;
  /* display: flex;
  justify-content: left; */
}

.customer-back {
  cursor: pointer;
  line-height: 62px;
  font-size: 16px;
  color: #323233;
  font-weight: 400;
}

.add-customer-btn {
  position: fixed;
  right: 36px;
  top: 115px;
}

::v-deep .el-form-item {
  margin-bottom: 0;
}

</style>
