<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 class="upper_right_button">
          <el-button type="success"
                     size="small"
                     class="el-button--small-yh "
                     :loading="buttonLoading"
                     :disabled="!form.id || viewDisabled"
                     @click.stop="mainCheck">
            请核
          </el-button>

<!--          <el-dropdown style="padding: 0 8px;line-height: 0">-->
<!--            <el-button-->
<!--              type="success"-->
<!--              :loading="buttonLoading"-->
<!--              :disabled="!form.id || viewDisabled"-->
<!--              size="small"-->
<!--            >-->
<!--              业务处理<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
<!--            </el-button>-->
<!--            <el-dropdown-menu slot="dropdown">-->
<!--              <el-dropdown-item-->
<!--                :loading="buttonLoading"-->
<!--                :disabled="!form.id"-->
<!--                @click.native="createData()">创建单据-->
<!--              </el-dropdown-item>-->
<!--              <el-dropdown-item-->
<!--                :loading="buttonLoading"-->
<!--                :disabled="!form.id"-->
<!--                @click.native="copyData()">复制单据-->
<!--              </el-dropdown-item>-->
<!--            </el-dropdown-menu>-->
<!--          </el-dropdown>-->

          <el-button class="el-button--small-yh "
                     type="primary"
                     :loading="buttonLoading"
                     @click.stop="editMainProject"
                     size="small"
          >保存数据
          </el-button>
        </div>
      </div>
    </div>
    <div class="customer-main">
      <containerTitle title="基础信息"></containerTitle>
      <basic-container>
        <avue-form class="trading-form" ref="form" v-model="form" :option="option">
          <template slot="corpId">
            <crop-select
              v-model="form.corpId"
              corpType="KG"
              :disabled="viewDisabled"
              style="width: 100%"
            ></crop-select>
          </template>
          <template slot="corpAttn">
            <el-select
              v-model="form.corpAttn"
              :disabled="viewDisabled"
              icon="el-icon-edit"
              remote
              filterable
              clearable
              :remote-method="corpAttnRemoteMethod"
            >
              <el-option
                v-for="item in corpAttnDic"
                :key="item.value"
                :label="item.realName"
                :value="item.realName">
              </el-option>
            </el-select>
          </template>
          <template slot="salesName">
            <el-select
              v-model="form.salesName"
              :disabled="viewDisabled"
              remote
              filterable
              clearable
              :remote-method="salesNameRemoteMethod"
            >
              <el-option
                v-for="item in salesNameDic"
                :key="item.value"
                :label="item.realName"
                :value="item.realName">
              </el-option>
            </el-select>
          </template>
          <template slot="sourceBusiness">
            <el-select
              v-model="form.sourceBusiness"
              :disabled="viewDisabled"
              filterable
              clearable
            >
              <el-option
                v-for="(item,index) in sourceBusinessDic"
                :key="index"
                :label="item.dictValue"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </template>
          <template slot="remark">
            <el-input type="textarea"
                      v-model="form.remark"
                      size="small"
                      rows="6"
                      autocomplete="off"
                      placeholder="">
            </el-input>
          </template>
        </avue-form>
      </basic-container>
      <containerTitle title="明细列表"></containerTitle>
      <basic-container>
        <avue-crud
          ref="crud"
          :data="data"
          :option="optionTable"
          :table-loading="loading"
          v-model="optionFrom"
          @row-del="rowDel"
          @row-save="rowSave"
          @row-update="rowUpdate"
          @size-change="sizeChange"
          @current-change="currentChange"
          @selection-change="selectionChange"
          @search-change="searchChange"
          @saveColumn="saveColumn"
        >
          <template slot="menuLeft">
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="原始数据" name="first" :key="'first'">
              </el-tab-pane>
              <el-tab-pane label="追加" name="second" :key="'second'">
              </el-tab-pane>
              <el-tab-pane label="退款" name="three" :key="'three'">
              </el-tab-pane>
            </el-tabs>
            <el-button type="primary"
                       size="small"
                       icon="el-icon-plus"
                       :disabled="viewDisabled"
                       @click="serviceDialog = true">录入明细
            </el-button>
          </template>
<!--            <el-button type="info"-->
<!--                       size="small"-->
<!--                       v-if="false"-->
<!--                       :disabled="crudSelection == 0"-->
<!--                       @click.stop="beforePleaseCheck()">请 核-->
<!--            </el-button>-->
<!--          </template>-->
          <template slot-scope="{row,index}"  slot="menu">
            <el-button
              v-if="row.status !== 5"
              type="text"
              size="small"
              @click="beforeCloseAccount(row)"
            >结算</el-button>
            <el-button
              v-if="row.status === 5"
              type="text"
              size="small"
              :disabled="viewDisabled"
              @click="cancelCloseAccount(row)"
            >取消结算</el-button>
            <el-button
              type="text"
              size="small"
              @click="rowCellTwo(row,index)"
              :disabled="row.strStatus == '结算完成' || viewDisabled"
            >{{row.$cellEdit?'修改完成':'修改'}}</el-button>
            <el-button
              type="text"
              size="small"
              @click="rowDel(row,index)"
              :disabled="row.strStatus == '结算完成' || viewDisabled"
            >删除</el-button>
          </template>
          <template slot="userid" slot-scope="{row,index}">
            <span v-if="row.$cellEdit" class="required_fields">*</span>
            <user-select
              style="width:90% !important;"
              v-if="row.$cellEdit"
              v-model="row.userName"
              @value="(values) => value(values,row)"
              :configuration="UConfiguration"
            >
            </user-select>
            <span v-else>{{ row.userName }}</span>
          </template>
          <template slot="amount" slot-scope="{ row }">
            <el-input
              v-if="row.$cellEdit"
              v-model="row.amount"
              placeholder="请输入"
              size="small"
              oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
              @change="totalChange(row,'金额')"
            ></el-input>
            <span v-else>{{ row.amount }}</span>
          </template>
          <template slot="serviceCharge" slot-scope="{ row }">
            <el-input
              v-if="row.$cellEdit"
              v-model="row.serviceCharge"
              placeholder="请输入"
              size="small"
              oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
              @input="costCount(row)"
              @change="totalChange(row,'服务')"
            ></el-input>
            <span v-else>{{ row.serviceCharge }}</span>
          </template>
          <template slot="matMoney" slot-scope="{ row }">
            <el-input
              v-if="row.$cellEdit"
              v-model="row.matMoney"
              placeholder="请输入"
              size="small"
              oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
              @input="costCount(row)"
              @change="totalChange(row,'代垫')"
            ></el-input>
            <span v-else>{{ row.matMoney }}</span>
          </template>
        </avue-crud>
      </basic-container>
      <containerTitle title="补充信息"></containerTitle>
      <basic-container>
        <el-form :model="formTwo" ref="formTwo" label-width="100px" class="demo-ruleForm">
          <el-row>
            <el-col v-for="(item, index) in basicData.column" :span="item.span?item.span:6" :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="formTwo[item.prop]" size="small" type="datetime" :disabled="item.disabled?true:false || viewDisabled" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss"/>
                <el-date-picker v-else-if="item.type === 'date'" style="width: 100%;" v-model="formTwo[item.prop]" size="small" type="date" :disabled="viewDisabled" placeholder="选择日期" value-format="yyyy-MM-dd"/>
                <el-input type="textarea" v-else-if="(item.prop === 'remark')" v-model="formTwo[item.prop]" :disabled="viewDisabled"  size="small" autocomplete="off" placeholder="请输入"></el-input>
                <el-input type="age" v-else-if="item.prop === 'debitAmount'" v-model="formTwo[item.prop]"  @change="debitChange"  :disabled="item.disabled?true:false || viewDisabled" size="small" autocomplete="off" placeholder="请输入">
                  <template   slot="append">元</template>
                </el-input>
                <el-input type="age" v-else-if="item.type === 'unit'" v-model="formTwo[item.prop]"   :disabled="item.disabled?true:false || viewDisabled" size="small" autocomplete="off" placeholder="请输入">
                  <template   slot="append">元</template>
                </el-input>
                <el-input type="age" v-else v-model="formTwo[item.prop]"  :disabled="item.disabled?true:false || viewDisabled" size="small" value="0" autocomplete="off" placeholder="请输入">
                  <template v-if="item.prop === 'advanceAmount'||item.prop === 'settlmentAmount'||item.prop === 'balanceAmount'"  slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </basic-container>
      <containerTitle title="附件上传"></containerTitle>
      <basic-container style="margin-bottom: 40px">
        <avue-crud
          :option="upLoadOption"
          v-model="upLoadForm"
          :data="upLoadData"
          @row-save="upLoadSave"
          @row-update="upLoadUpdate"
          @row-del="upLoadDel"
        ></avue-crud>
      </basic-container>
    </div>
    <el-dialog
      title="导入服务项目"
      append-to-body
      class="el-dialogDeep"
      :visible.sync="serviceDialog"
      width="70%"
      :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="serviceTreeOption"  @node-click="serviceNodeClick"/>
              </basic-container>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19">
          <basic-container>
            <avue-crud ref="serviceCrud"
                       :page.sync="servicePage"
                       :search.sync="serviceSearch"
                       :option="serviceOption"
                       :table-loading="serviceLoading"
                       :data="serviceData"
                       @refresh-change="serviceRefreshChange"
                       @selection-change="serviceSelectionChange"
                       @search-change="serviceSearchChange"
                       @on-load="serviceOnLoad">
            </avue-crud>
          </basic-container>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="serviceConfirm()" :disabled="this.serviceSelectList.length == 0">导 入</el-button>
         <el-button @click="serviceDialog = false">取 消</el-button>
        </span>
    </el-dialog>
    <el-dialog
      title="导入用户"
      :visible.sync="userDialog"
      class="el-dialogDeep"
      append-to-body
      width="80%">
      <el-row style="margin-top: -5px;height: 0">
        <el-col :span="5">
          <div class="box">
            <el-scrollbar>
              <basic-container>
                <avue-tree :option="userTreeOption" :data="userTreeData" @node-click="userNodeClick"/>
              </basic-container>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19">
          <basic-container>
            <avue-crud ref="userCrud"
                       :option="userOption"
                       :data="userDataList"
                       :table-loading="userLoading"
                       :page.sync="userPage"
                       v-model="userForm"
                       @search-change="userSearchChange"
                       @search-reset="userSearchReset"
                       @refresh-change="userRefreshChange"
                       @selection-change="userSelectionChange"
                       @on-load="userOnLoad"
            >
            </avue-crud>
          </basic-container>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
      <el-button @click="userDialog = false">取 消</el-button>
      <el-button type="primary" :disabled="this.userSelection.length == 1 ? false:true" @click="userConfirm" >确 定</el-button>
    </span>
    </el-dialog>
    <el-dialog
      title="流程"
      append-to-body
      class="el-dialogDeep"
      :visible.sync="processDialog"
      width="60%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :modal-append-to-body='false'
      :close-on-press-escape="false"
      v-dialog-drag
    >
      <examine-approve
        :itemId ="itemId"
        :closeFun="dialogProcessClose"
      >
      </examine-approve>
    </el-dialog>
    <el-dialog
      title="结算"
      append-to-body
      class="el-dialogDeep"
      :visible.sync="accountDialog"
      width="25%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false">
      <el-form  :model="accountFormData" ref="accountFormData">
        <el-form-item label="账户名称"  class="landConFrom-input" prop="accountName" :rules="rules">
          <el-input v-model="accountFormData.accountName" style="width: 220px;" size="small" clearable  placeholder="请输入" ></el-input>
        </el-form-item>
        <el-form-item label="结算日期"  class="landConFrom-input" prop="payTime"  :rules="rules">
          <el-date-picker type="date" v-model="accountFormData.payTime" value-format="yyyy-MM-dd HH:mm:ss"  size="small" clearable  placeholder="日期" ></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" style="display: flex; justify-content: center">
          <el-button @click.stop="accountDialog = false , accountFormData = {}" size="small">取 消</el-button>
          <el-button type="primary"  size="small" @click="closeAccount('accountFormData')">结算</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import option from "./configuration/detailsPage.json";
  import startOption from "./configuration/startDialog.json";
  import { projectDetail,editMianProject,settleAccounts,getSysNo,masterCheck} from "@/api/workManagement/mainProject";
  //上传文件json
  import upLoadOption from "../../exportTrade/purchaseContract/config/uploadList.json"
  //服务列表接口
  import {getServiceProjectList,getServiceTypeTree,} from "@/api/workManagement/serviceProject";
  import serviceOption from "./configuration/serviceDialogList.json";
  //用户组件
  import userOption from "./configuration/userList.json";
  import { getList } from "@/api/system/user";
  import { getDeptLazyTree} from "@/api/system/dept";

  //上传附件删除
  import { corpsbank } from "@/api/basicData/configuration"
  //事务
  import examineApprove from "@/components/examineApprove/index";
  //对象数组比较
  import { contrastObj,contrastList } from "@/util/contrastData";
  import _ from "lodash";
  import { getUserList } from "@/api/workManagement/mainProject";
  import optionAdd from "../receipt/configuration/settleAccountsDetailsADD.json";
  import optionReturn from "../receipt/configuration/settleAccountsDetailsReturn.json";



  export default {
    props: {
      detailData: {
        type: Object
      }
    },
    data() {
      return {
        id:'',
        loading: false,
        form:{},
        formTwo:{},
        optionFrom:{},
        account:{},
        data:[],
        dataList:[],
        crudSelection:[],
        corpAttnDic:[],
        salesNameDic:[],
        sourceBusinessDic:[],
        buttonLoading:false,
        viewDisabled:false,
        deptDicData:[],//任务部门数据
        serviceDialog:false,//服务导入窗口
        userDialog:false,//用户导入窗口
        accountDialog:false,//结算窗口
        //客户组件配置控制
        UConfiguration:{
          multipleChoices:false,
          multiple:false,
          disabled:false,
          searchShow:true,
          collapseTags:false,
          placeholder:'请点击右边按钮选择',
          dicData:[]
        },
        detailsSelect: {},
        //顶部from数据
        option: {
          menuBtn: false,
          labelWidth: 100,
          column: [
            {
              label: '项目名称',
              prop: 'cname',
              span: 12,
              rules: [
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '客户名称',
              prop: 'corpId',
              span: 12,
              rules: [
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '责任人',
              prop: 'corpAttn',
              span: 6,
              rules: [
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '承揽人',
              prop: 'salesName',
              span: 6,
              rules: [
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '业务来源',
              prop: 'sourceBusiness',
              span: 6,
              rules: [
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '备注',
              span: 24,
              minRows: 6,
              prop: 'remark'
            }
          ],
        },
        basicData: {
          column: [
            {
              label: '合同金额',
              prop: 'debitAmount',
              rules: [
                {
                  required: false,
                  message: ' ',
                  trigger: 'blur'
                },
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: ' ',
                  trigger: 'blur'
                },
              ]
            },
            {
              label: '首付金额',
              prop: 'advanceAmount',
              type:'unit',
              rules: [
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '已收金额',
              prop: 'settlmentAmount',
              disabled: true,
              type:'unit',
            },
            {
              label: '未收金额',
              type:'unit',
              prop: 'balanceAmount',
              disabled: true,
            },
            {
              label: '总服务费',
              prop: 'serviceCharge',
              type:'unit',
              disabled: true,
              rules: [
                {
                  pattern:/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '总代垫费',
              prop: 'matMoney',
              type:'unit',
              disabled: true,
              rules: [
                {
                  pattern:/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '制单人',
              prop: 'createUserName',
              disabled: true
            }, {
              label: '制单日期',
              prop: 'createTime',
              type: 'datetime',
              valueFormat:"yyyy-MM-dd HH:mm:ss",
              format:"yyyy-MM-dd",
              disabled: true
            },
            {
              label: '电话',
              prop: 'corpTel',
            },
            {
              label: '收款方式',
              prop: 'paymentType',
              width: 120,
            },
            {
              label: '开始日期',
              prop: 'beginTime',
              valueFormat:"yyyy-MM-dd HH:mm:ss",
              format:"yyyy-MM-dd",
              type:'datetime',
            },
            {
              label: '结束日期',
              prop: 'endTime',
              valueFormat:"yyyy-MM-dd HH:mm:ss",
              format:"yyyy-MM-dd",
              type:'datetime',
            }
          ],
        },
        optionTable: option,
        //结算
        accountFormData:{},
        rules:[{
          required: true,
          message: ' ',
          trigger: 'blur'
        }
        ],
        //上传文件
        upLoadOption: upLoadOption,
        upLoadData:[],
        upLoadForm:{},
        //服务窗口定义
        serviceTreeOption: {
          nodeKey: 'id',
          lazy: true,
          treeLoad: function(node, resolve) {
            const parentId = node.level === 0 ? 0 : node.data.id;
            getServiceTypeTree(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'
          }
        },
        serviceOption:serviceOption,
        serviceLoading:false,
        serviceData:[],
        servicePage:{
          currentPage: 1,
          total: 0,
          pageSize: 10
        },
        serviceSearch:{},
        serviceTreeDeptId:"",
        serviceSelectList:[],
        //用户窗口定义
        userTreeOption: {
          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'
          }
        },
        userTreeData:[],
        userOption:userOption,
        userLoading:false,
        userDataList:[],
        userSelection:[],
        userTreeDeptId:"",
        userForm:{},
        userPage:{
          currentPage: 1,
          total: 0,
          pageSize: 10
        },
        itemId:'',
        //请核窗口定义
        processDialog:false,
        pleaseCheckContact:startOption,
        pleaseCheckLoading:false,
        pleaseCheckData:[],
        pleaseCheckPage:{
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        activeName: "first",
        tab1:true,
        tab2:false,
        tab3:false,
        secondDisable:0,
        data_one:[],
        data_two:[],
        data_three:[],
        //新旧数据比较
        oldData:[],
        oldUpLoadData:[],
        oldForm:{},
        oldFormTwo:{},
      };
    },
    created() {

      //承揽人 责任人 默认20条数据
      getUserList().then(res=>{
        res.data.data.map((item,index)=>{
          if(index <= 20){
            this.corpAttnDic.push(item)
            this.salesNameDic.push(item)
          }
        })
      })

      //字典值
      this.getWorkDicts("source_Business").then(res =>{
        this.sourceBusinessDic = res.data.data;
      })

      if(this.detailData.id){
        this.id = BigInt(this.detailData.id);//字符串转数字  超长用BigInt

        projectDetail(this.id,"0,1,2,3,4,5").then(res =>{
          this.afterEcho(res.data.data)
        })

      }else{
        //责任人  承揽人 默认当前登录人
        this.$set(this.formTwo,"corpAttn",this.$store.getters.userInfo.user_name)
        this.$set(this.formTwo,"salesName",this.$store.getters.userInfo.user_name)

        this.$set(this.formTwo,"debitAmount",0)
        this.$set(this.formTwo,"advanceAmount",0)
        this.$set(this.formTwo,"settlmentAmount",0)
        this.$set(this.formTwo,"balanceAmount",0)
        this.$set(this.formTwo,"createUserName", this.$store.getters.userInfo.user_name)

        let date = new Date();
        let strDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
        this.$set(this.formTwo,"createTime",strDate)

      }
      if(this.$route.query.itemId){
        this.id = this.$route.query.itemId
        projectDetail(this.id,"0,1,2,3,4,5").then(res =>{
          this.afterEcho(res.data.data)
        })
      }
    },
    components:{
      examineApprove
    },
    mounted() {

    },
    methods: {
      //明细切换tab
      handleClick(tab) {
        if(tab.name == "first") {
          this.tab1 = true;
          this.tab2 = false;
          this.tab3 = false;
          if(this.secondDisable === 1){
            this.data_two = this.data
          }
          if(this.secondDisable === 2){
            this.data_three = this.data
          }

          this.secondDisable = 0
          this.optionTable = option  //换option
          this.data = this.data_one  //切换数据
        } else if(tab.name == "second") {

          this.tab1 = false;
          this.tab2 = true;
          this.tab3 = false;

          if(this.secondDisable === 0){
            this.data_one = this.data
          }
          if(this.secondDisable === 2){
            this.data_three = this.data
          }

          this.secondDisable = 1
          this.optionTable = optionAdd
          this.data = this.data_two
        }else if(tab.name == "three") {
          this.tab1 = false;
          this.tab2 = false;
          this.tab3 = true;
          if(this.secondDisable === 0){
            this.data_one = this.data
          }
          if(this.secondDisable === 1){
            this.data_two = this.data
          }

          this.secondDisable = 2
          this.optionTable = optionReturn
          this.data = this.data_three
        }
      },
      //责任人 远程
      corpAttnRemoteMethod(val){
        getUserList({realName : val}).then(res=>{
          this.corpAttnDic = res.data.data
        })
      },
      //承揽人 远程
      salesNameRemoteMethod(val){
        getUserList({realName : val}).then(res=>{
          this.salesNameDic = res.data.data
        })
      },
      value(value,row){
        row.userid = value.id
        row.deptid = value.deptId
      },
      //合计
      totalChange(row,type){

        //明细列表金额合计
        if(this.secondDisable === 0){
          this.data_one = this.data
        }
        let amountList =  this.data_one.map(item => {
          if(item.amount){
            return parseFloat(item.amount);
          }else return 0
        });
        //明细列表服务费合计
        let serviceChargeList =  this.data.map(item => {
          if(item.serviceCharge){
            return parseFloat(item.serviceCharge);
          }else return 0
        });
        //明细列表代垫费合计
        let matMoneyList =  this.data.map(item => {
          if(item.matMoney){
            return parseFloat(item.matMoney);
          }else return 0
        });
        if(type==='金额'){
          if(this.formTwo.debitAmount){
            if(this.formTwo.debitAmount < amountList.reduce((n,m) => n + m)){
              this.$message.error("明细列表合同金额不能大于总金额!")
            }
          }
        }
        // if(type==='服务'){
        //   this.formTwo.serviceCharge = serviceChargeList.reduce((n,m) => n + m)
        // }
        // if(type==='代垫'){
        //   this.formTwo.matMoney = matMoneyList.reduce((n,m) => n + m)
        // }
        if(row.serviceCharge && row.matMoney){
          if(row.amount <  _.add(parseFloat(row.serviceCharge),parseFloat(row.matMoney))){
            this.$message.error("服务费代垫费不能超过合同金额!")
            row.serviceCharge = 0;
            row.matMoney = 0;
          }
        }
      },
      //费用计算计算
      costCount(row){
        if(row.serviceCharge && row.matMoney){
           row.amount = _.add(parseFloat(row.serviceCharge),parseFloat(row.matMoney));
        }
      },
      //删除列表后面的删除按钮触发触发(row, index, done)
      rowDel(row, index) {
        this.$confirm("确定将此明细删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.data.splice(index,1)
        });
      },
      // 合同金额
      debitChange(val){
        if(val){
          if(!this.formTwo.settlmentAmount){
            this.$set(this.formTwo,"balanceAmount",val)
          }
        }
      },
      //打开结算窗口
      beforeCloseAccount(row){
        if(this.verificationData()){
          this.account = row;
          this.accountDialog = true;
        }
      },
      //结算
      closeAccount(form){
        this.$refs[form].validate((valid) => {
          if(valid){
            settleAccounts(this.account.id,5,
              this.accountFormData.accountName,
              this.accountFormData.payTime,).then(res =>{
              if(res.data.success){
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                this.accountFormData = {},
                  this.accountDialog = false;
                this.getProjectDetail();
              }
            })
          }
        })
      },
      cancelCloseAccount(row){
        this.$confirm("确认取消结算此明细?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          settleAccounts(row.id,6).then(res =>{
            if(res.data.success){
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.getProjectDetail();
            }
          })
        });
      },
      //请核
      mainCheck(){
        if(this.verificationData()){
          this.detailsCollection()
          for (let i = 0; i < this.dataList.length; i++) {
            if (this.dataList[i].strStatus !== "结算完成") {
              return this.$message.error(`明细列表存在未结算数据,请检查!`);
            }
          }

          masterCheck(this.form.id).then(res=>{
            if(res.data.success){
              this.$message.success("操作成功!")
              this.getProjectDetail();
            }
          })
        }
        //
      },
      getProjectDetail(){
        projectDetail(this.id,"0,1,2,3,4,5").then(res =>{
          this.afterEcho(res.data.data)
        })
      },
      //新增 修改
      editMainProject(type){
        this.$refs["form"].validate((valid)  => {
          if(valid){
            this.detailsCollection()
            for (let i = 0; i < this.dataList.length; i++) {
              if (this.dataList[i].userid === (null || "")) {
                return this.$message.error(`请输入明细列表第${i + 1}行的承做人`);
              }
              if (this.dataList[i].deptid === (null || "")) {
                return this.$message.error(`请输入明细列表第${i + 1}行的任务部门`);
              }
              if (this.dataList[i].beginTime === (null || "")) {
                return this.$message.error(`请输入明细列表第${i + 1}行的开始日期`);
              }
              if (this.dataList[i].actualDate === (null || "")) {
                return this.$message.error(`请输入明细列表第${i + 1}行的结束`);
              }
            }
            this.buttonLoading = true

            const params = {
              ...this.form,
              ...this.formTwo,
              itemList:this.dataList,
              filesList:this.upLoadData
            }

            editMianProject(params).then(res =>{
              if(res.data.success){
                this.id = res.data.data
                this.$message.success("操作成功!")
                projectDetail(res.data.data,"0,1,2,3,4,5").then(res =>{
                  this.afterEcho(res.data.data)
                })
              }
            }).finally(()=>{
              this.buttonLoading = false
            })
            if(type === true){
              this.$emit("goBack");
            }
          }
        })
      },
      copyData(){
        if(this.verificationData()){
          delete this.form.id
          delete this.formTwo.id
        }
      },
      createData(){
        if(this.verificationData()){
          this.$confirm("确定创建新的单据吗?", "提示", {
            confirmButtonText: "保存",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.form = {}
            this.oldForm = {}
            this.formTwo = {}
            this.oldFormTwo = {}
            this.dataList = []
            this.oldData = []
            this.upLoadData = []
            this.oldUpLoadData = []

            this.$set(this.formTwo,"corpAttn",this.$store.getters.userInfo.user_name)
            this.$set(this.formTwo,"salesName",this.$store.getters.userInfo.user_name)

            this.$set(this.formTwo,"debitAmount",0)
            this.$set(this.formTwo,"advanceAmount",0)
            this.$set(this.formTwo,"settlmentAmount",0)
            this.$set(this.formTwo,"balanceAmount",0)
            this.$set(this.formTwo,"createUserName", this.$store.getters.userInfo.user_name)

            let date = new Date();
            let strDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
            this.$set(this.formTwo,"createTime",strDate)
          })
        }
      },
      //明细合集
      detailsCollection(){
        if(this.secondDisable === 0){
          this.data =  this.data_one
        }
        if(this.secondDisable === 1){
          this.data =  this.data_two
        }
        if(this.secondDisable === 2){
          this.data =  this.data_three
        }

        this.dataList = []
        this.dataList.push(...this.data_one,...this.data_two,...this.data_three)
      },
      afterEcho(data){
        this.form = data;
        this.viewDisabled =  this.form.status !== 0? true : false
        this.option.column.forEach(item =>{
          if( item.prop == "cname" ){
            this.$set(item,"disabled",this.viewDisabled)
          }
        })

        this.formTwo = Object.assign({},data);

        delete this.formTwo.cname;
        delete this.formTwo.corpId;
        delete this.formTwo.corpAttn;
        delete this.formTwo.salesName;
        delete this.formTwo.sourceBusiness;
        delete this.formTwo.remark;

        this.oldForm = Object.assign({},data);
        this.oldFormTwo = Object.assign({},data);

        if(data.itemList){
          this.dataList = data.itemList;
          this.oldData = this.deepClone(data.itemList)

          //根据状态区分三种明细
          this.data_one=this.dataList.filter(item=>item.projectType === 0)
          this.data_two=this.dataList.filter(item=>item.projectType === 1)
          this.data_three=this.dataList.filter(item=>item.projectType === 2)

          //判断当前所处哪个明细下  给data赋值
          if(this.secondDisable === 0){
            this.data =  this.data_one
          }
          if(this.secondDisable === 1){
            this.data =  this.data_two
          }
          if(this.secondDisable === 2){
            this.data =  this.data_three
          }
        }
        if(data.filesList){
          this.upLoadData = data.filesList
          this.oldUpLoadData = this.deepClone(data.filesList)
        }
      },
      verificationData(){
        this.detailsCollection()
        if(contrastObj(this.form,this.oldForm)||contrastObj(this.formTwo,this.oldFormTwo) || contrastList(this.dataList,this.oldData)
          || contrastList(this.upLoadData,this.oldUpLoadData)
        ) {
          this.$confirm("数据发生变化，请先提交保存!", "提示", {
            confirmButtonText: "保存",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.editMainProject()
          }).catch(()=>{
            return false
          })
        }else{
          return true
        }
      },
      //点击修改或保存时触发
      rowCellTwo(row,index){
        this.$refs.crud.rowCell(row, index);
      },
      //选择时
      selectionChange(row){
        this.crudSelection = row;
      },
      //新增修改时保存触发
      rowSave(row, done, loading) {
        done()
      },
      rowUpdate(row, index, done, loading) {
        done(row)
      },
      searchChange(params, done) {
        this.getList(this.page, params);
        done();
      },
      sizeChange(val) {
        this.page.pageSize = val;
        this.getList();
      },
      currentChange(val) {
        this.page.currentPage = val;
        this.getList();
      },
      saveColumn(row, column) {
        console.log(row, column);
      },
      //上传文件保存
      upLoadSave(row, done, loading){
        this.upLoadData.push(row)
        done()
      },
      //修改附件上传触发
      upLoadUpdate(row, done){
        done(row);
      },
      //删除附件上传触发
      upLoadDel(row, index,){
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          if (row.id){
            corpsbank(row.id).then(res=>{
              if(res.data.success){
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                this.bankOfDepositData.splice(index, 1);
              }
            })
          }else {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.bankOfDepositData.splice(index, 1);
          }
        })
      },
      //服务窗口事件
      serviceNodeClick(data) {
        this.serviceTreeDeptId = data.id;
        this.serviceOnLoad(this.servicePage);
      },
      serviceRefreshChange(){
        this.serviceOnLoad(this.servicePage, this.serviceSearch)
      },
      serviceSearchChange(params, done){
        this.serviceOnLoad(this.servicePage, params)
        done();
      },
      serviceSelectionChange(row){
        this.serviceSelectList = row;
      },
      serviceOnLoad(page, params = {}) {
        this.serviceLoading = true;
        getServiceProjectList(page.currentPage, page.pageSize, params, this.serviceTreeDeptId).then(res => {
          this.serviceData = res.data.data.records
          this.servicePage.total = res.data.data.total
          this.serviceLoading = false
        })
      },
      serviceConfirm(){
        if(this.serviceSelectList.length != 0){
          this.serviceSelectList.forEach((item)=>{
            const params = {
              strStatus:"录入",
              pname:item.cname,
              remarks:item.remarks,
              price:item.price,
              unit:item.unit,
              secondDisable:this.secondDisable,
              frequency:item.rate,
              projectType:this.secondDisable
            }
            this.$refs.crud.rowCellAdd(params);
            this.$refs.crud.rowCell(item, this.optionFrom.length-1)
          })
        }
        this.serviceSelectList = []
        this.serviceDialog = false
        this.$message({
          type: "success",
          message: "导入成功!"
        });
      },
      //用户窗口事件
      selectUser(row){
        this.userDialog = true
        this.detailsSelect = row.$index;
      },
      userSearchChange(params, done){
        this.userOnLoad(this.userPage, params);
        done()
      },
      userSearchReset(){

      },
      userRefreshChange(){
        this.userOnLoad(this.userPage)
      },
      userSelectionChange(row){
        this.userSelection = row;
      },
      userOnLoad(page,params={}){
        this.userLoading = true;
        getList(page.currentPage, page.pageSize, params, this.userTreeDeptId).then(res => {
          this.userDataList = res.data.data.records
          this.userPage.total = res.data.data.total
          this.userLoading = false;
        });
      },
      userNodeClick(data){
        this.userTreeDeptId = data.id;
        this.userOnLoad(this.userPage);
      },
      //确定
      userConfirm(){
         if(this.userSelection){
           this.data[this.detailsSelect].userid = this.userSelection[0].id;
           this.$set(this.data[this.detailsSelect],'userName',this.userSelection[0].realName)
           this.userDialog = !this.userDialog
         }
      },
      dialogProcessClose(){
        this.processDialog = false
        this.getProjectDetail()
      },
      //返回主营项目列表
      backToList(){
        this.detailsCollection()
        if(contrastObj(this.form,this.oldForm) || contrastObj(this.formTwo,this.oldFormTwo) || contrastList(this.dataList,this.oldData)
          || contrastList(this.upLoadData,this.oldUpLoadData)
        ){
          this.$confirm("当前页面有未保存数据，是否保存数据？", "提示", {
            confirmButtonText: "保存",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.editMainProject(true)
          }).catch(()=>{
            this.$emit("goBack");
          })
        }else{
          this.$emit("goBack");
        }
      },



      //1.0版本注释内容
      // operationDetailList(itemList){
      //   this.data = itemList;
      //   this.oldData = this.deepClone(itemList)
      //   let status = [];
      //   this.data.forEach(item =>{
      //     item.status == 0 ? status.push(true) : status.push(false)
      //   })
      //   //如果 明细列表存在 请核之后的状态 禁止编辑一些输入框
      //   if(status.findIndex(item => item == false) == 0){
      //     this.basicData.column.forEach(item =>{
      //       if(item.prop == "code" || item.prop == "cname" || item.prop == "corpId" || item.prop == "debitAmount"){
      //         item.disabled = true
      //         this.configuration.disabled = true
      //       }
      //     })
      //   }else{
      //     this.basicData.column.forEach(item =>{
      //       if(item.prop == "code" || item.prop == "cname" || item.prop == "corpId" || item.prop == "debitAmount"){
      //         item.disabled = false
      //         this.configuration.disabled = false
      //       }
      //     })
      //   }
      // },
      // openPleaseCheckDialog(){
      //   this.processDialog = true;
      //   this.itemId = this.crudSelection[0].id   //记得不能写死
      // },
      // //请核之前
      // beforePleaseCheck(){
      //   if(this.crudSelection){
      //     let id = [];
      //     let result = [];
      //     this.crudSelection.forEach(item=>{
      //       // 新录入状态下  才可提交审核
      //       item.id ? id.push(true) : id.push(false) //如果没有id并且为新录入  提示保存
      //       item.strStatus === "录入" ? result.push(true) : result.push(false) //判断所有的是否为录入状态
      //     })
      //     if(id.findIndex(item => item != true) == -1){
      //       if(result.findIndex(item => item != true) == -1){
      //         if(contrastObj(this.form,this.oldForm) || contrastList(this.data,this.oldData)){  //判断是否改动过此页面
      //           this.$confirm("您已改动此页面,请先保存之后在请核？", "提示", {
      //             confirmButtonText: "保存",
      //             cancelButtonText: "取消",
      //             type: "warning",
      //           }).then(() => {
      //             this.editMainProject();
      //           }).catch(()=>{
      //             return
      //           })
      //         }else{
      //           this.pleaseCheck()
      //           // this.openPleaseCheckDialog();
      //         }
      //       }else{
      //         this.$message({
      //           type: "error",
      //           message: "请核数据中存在已请核数据!"
      //         });
      //         return
      //       }
      //     }else{
      //       this.$confirm("列表内存在新录入数据,是否先保存此数据?", {
      //         confirmButtonText: "确定",
      //         cancelButtonText: "取消",
      //         type: "warning"
      //       }).then(() => {
      //         this.editMainProject();
      //       })
      //     }
      //   }
      // },
      // //请核
      // pleaseCheck(){
      //   this.crudSelection.forEach(item =>{
      //     updateItemStatus(this.data[item.$index].id,1).then(res =>{
      //
      //     })
      //     this.$message({
      //       type: "success",
      //       message: "请核成功!"
      //     });
      //     //刷新列表
      //     this.getProjectDetail();
      //   })
      // },
    },
    watch:{
      dataList:function (list) {

      }
    }
  };
</script>

<style scoped lang="scss">
  .main-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;
  }
  .upper_right_button{
    display: flex;
    position: fixed;
    right: 12px;
    top: 47px;
  }
  .main-back {
    cursor: pointer;
    line-height: 62px;
    font-size: 16px;
    color: #323233;
    font-weight: 400;
  }
  .required_fields{
    color: #F56C6C;
    display:inline-block;
    width: 7%
  }
  .avue-tree {
    overflow: hidden;
    max-height: 660px;
  }
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
  ::v-deep .el-form-item__content{
    line-height: 32px;
  }
  .trading-form ::v-deep .el-form-item {
    margin-bottom: 8px !important;
  }
  .landConFrom-input{
    display:flex;
    justify-content:center;
  }
</style>
