<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>
        <el-button class="el-button--small-yh add-customer-btn"
                   size="small"
                   type="primary"
                   @click.stop="editMainProject"
        >{{this.id?"确认修改" :"确认新增"}}
        </el-button>
      </div>
    </div>
    <div style="margin-top: 60px">
      <containerTitle title="基础信息"></containerTitle>
      <basic-container >
        <el-form :model="form" ref="form" label-width="130px">
          <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'" :disabled="item.disabled?true:false" 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.prop === 'paymentType'" :disabled="item.disabled?true:false" style="width: 100%" v-model="form[item.prop]" size="small" placeholder="请选择" clearable filterable >
                  <el-option v-for="(item,index) in paymentTerm" :key="index" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
                <el-input type="age" v-else-if="item.type === 'unit'" v-model="form[item.prop]" :disabled="item.disabled?true:false" size="small" autocomplete="off" placeholder="请输入">
                  <template   slot="append">元</template>
                </el-input>
                <selectComponent v-else-if="item.prop === 'corpId'" :disabled="item.disabled?true:false"  v-model="form[item.prop]" :configuration="configuration"/>
                <el-input type="textarea" v-else-if="(item.prop === 'remark'||item.prop === 'settlementRemark')" v-model="form[item.prop]" :disabled="item.disabled && item.prop === 'remark'?true:false"  size="small" autocomplete="off" placeholder="请输入"></el-input>
                <el-input type="age" v-else v-model="form[item.prop]" :disabled="item.disabled?true:false" size="small" autocomplete="off" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </basic-container>
      <containerTitle title="明细列表"></containerTitle>
      <basic-container>
        <avue-crud :option="option"
                   :data="dataList"
                   ref="crud"
                   v-model="form"
                   :page.sync="page"
                   :table-loading="loading"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @row-update="rowUpdate"
                   @refresh-change="refreshChange">
          <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>
          </template>
          <template slot="menuRight">
            <el-button
              type="primary"
              size="small"
              v-if="secondDisable == 1  || secondDisable == 2 "
              @click.stop="serviceDialog = true"
            >录入明细
            </el-button>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.status == 5"
              v-if="secondDisable == 1  || secondDisable == 2 "
              @click="rowCell(scope.row,scope.index)"
            >{{ scope.row.$cellEdit ? '修改完成' : '修改' }}
            </el-button>
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.status == 5"
              v-if="secondDisable == 1  || secondDisable == 2 "
              @click="rowDel(scope.row,scope.index)"
            >删除
            </el-button>
            <el-button
              type="text"
              icon="el-icon-check"
              size="small"
              :disabled="!scope.row.id"
              v-if="scope.row.status != 5 && (scope.row.status == 4 || secondDisable == 1  || secondDisable == 2)"
              @click.stop="beforeCloseAccount(scope.row,scope.index)"
            >结 算
            </el-button>
            <el-button
              type="text"
              icon="el-icon-close"
              size="small"
              v-if="scope.row.status == 5"
              @click.stop="callAccount(scope.row,scope.index)"
            >取消结算
            </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")'
            ></el-input>
            <span v-else>{{ row.amount }}</span>
          </template>
          <template slot="serviceCharge" slot-scope="{ row }">
            <span v-if="row.$cellEdit" class="required_fields">*</span>
            <el-input
              v-if="row.$cellEdit"
              v-model="row.serviceCharge"
              style="width:90% !important;"
              placeholder="请输入"
              size="small"
              oninput='this.value=this.value.replace(/[^(\-?\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
              @input="costCount(row)"
            ></el-input>
            <span v-else>{{ row.serviceCharge }}</span>
          </template>
          <template slot="matMoney" slot-scope="{ row }">
            <span v-if="row.$cellEdit" class="required_fields">*</span>
            <el-input
              v-if="row.$cellEdit"
              v-model="row.matMoney"
              style="width:90% !important;"
              placeholder="请输入"
              size="small"
              oninput='this.value=this.value.replace(/[^(\-?\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
              @input="costCount(row)"
            ></el-input>
            <span v-else>{{ row.matMoney }}</span>
          </template>
          <template slot="costReturn" slot-scope="{ row }">
            <span v-if="row.$cellEdit" class="required_fields">*</span>
            <el-input
              v-if="row.$cellEdit"
              style="width:90% !important;"
              v-model="row.costReturn"
              placeholder="请输入"
              size="small"
              oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
            ></el-input>
            <span v-else>{{ row.costReturn }}</span>
          </template>
          <template slot="superaddition" slot-scope="{ row }">
            <span v-if="row.$cellEdit" class="required_fields">*</span>
            <el-input
              v-if="row.$cellEdit"
              style="width: 90%"
              v-model="row.superaddition"
              placeholder="请输入"
              size="small"
              oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
            ></el-input>
            <span v-else>{{ row.superaddition }}</span>
          </template>
        </avue-crud>
      </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"
      :modal-append-to-body='false'
      :close-on-press-escape="false"
      v-dialog-drag
    >
      <service-component
        @serviceConfirm="serviceConfirm"
        @choce="choce"
      >
      </service-component>
    </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/settleAccountsDetailsPage.json";
  import optionAdd from "./configuration/settleAccountsDetailsADD.json";
  import optionReturn from "./configuration/settleAccountsDetailsReturn.json";
  import upLoadOption from "../../exportTrade/purchaseContract/config/uploadList.json";
  import { projectDetail,editMianProject,updateItemStatus } from "@/api/workManagement/mainProject";
  //业务字典
  import { getDictionary } from "@/api/system/dictbiz";
  //上传附件删除
  import { corpsbank } from "@/api/basicData/configuration"
  import serviceComponent from "@/components/mainProject/index"
  import _ from "lodash";


  export default {
    name: "customerInformation",
    props: {
      detailData: {
        type: Object
      }
    },
    components:{
      serviceComponent
    },
    data() {
      return {
        loading:false,
        accountDialog:false,
        serviceDialog:false,
        activeName: "first",
        tab1:true,
        tab2:false,
        tab3:false,
        secondDisable:0,
        aaccount:{},
        form: {},
        accountFormData:{
        },
        rules:[{
          required: true,
          message: ' ',
          trigger: 'blur'
        }
        ],
        UConfiguration:{
          multipleChoices:false,
          multiple:false,
          disabled:false,
          searchShow:true,
          collapseTags:false,
          placeholder:'请点击右边按钮选择',
          dicData:[]
        },
        option: option,
        parentId:0,
        account:{},
        paymentTerm:[],
        selectList:[],

        page: {
          pageSize: 10,
          pagerCount: 5,
          total: 0,
        },
        configuration:{
          multipleChoices:false,
          multiple:false,
          disabled:true,
          searchShow:false,
          collapseTags:false,
          placeholder:'请点击右边按钮选择',
          dicData:[]
        },
        query:{},
        //顶部from数据
        basicData: {
          column: [
            {
              label: '项目名称',
              prop: 'cname',
              span:12,
              disabled: true,
              rules: [
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            }, {
              label: '客户名称',
              span:12,
              prop: 'corpId',
              disabled: true,
            },{
              label: '合同金额',
              prop: 'debitAmount',
              type:'unit',
              disabled: true,
              rules: [
                {
                  pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '首付金额',
              prop: 'advanceAmount',
              type:'unit',
              disabled: true,
              rules: [
                {
                  pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '未收金额',
              prop: 'balanceAmount',
              type:'unit',
              disabled: true,
              rules: [
                {
                  pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '已收金额',
              prop: 'settlmentAmount',
              type:'unit',
              disabled: true,
              rules: [
                {
                  pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              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: 'corpAttn',
              disabled: true
            }, {
              label: '承揽人',
              prop: 'salesName',
              disabled: true
            },
            {
              label: '制单人',
              prop: 'createUserName',
              disabled: true
            }, {
              label: '制单日期',
              prop: 'createTime',
              type: 'datetime',
              disabled: true
            },
            {
              label: '电话',
              prop: 'corpTel',
              disabled: true,
            },
            {
              label: '收款方式',
              prop: 'paymentType',
              type:'select',
              dataType: "number",
              width: 120,
              disabled: true,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=affair_payment_term",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
            },
            {
              label: '开始日期',
              disabled: true,
              prop: 'beginTime',
              type:'datetime',
            },
            {
              label: '结束日期',
              disabled: true,
              prop: 'endTime',
              type:'datetime',
            },
            {
              label: '备注',
              span: 24,
              prop: 'remark',
              disabled: true,
            },
            {
              label: '结算备注',
              span: 24,
              prop: 'settlementRemark',
              disabled: true,
            },
          ],
        },
        dataList: [],
        allDataList:[],
        data_one:[],
        data_two:[],
        data_three:[],
        //上传文件
        upLoadOption: upLoadOption,
        upLoadData:[],
        upLoadForm:{},
      }
    },
    created() {
      this.id = this.detailData.id;
      this.getProjectDetail();
      const params = {
        code : "affair_payment_term"
      }
      getDictionary(params).then(res =>{
        this.paymentTerm = res.data.data;
      })
    },
    mounted() {

    },
    methods: {
      value(value,row){
        row.userid = value.id
        row.deptid = value.deptId
      },
      costCount(row){
        if(row.serviceCharge && row.matMoney){
          row.amount = _.add(parseFloat(row.serviceCharge),parseFloat(row.matMoney));
        }
      },
      handleClick(tab) {
        if(tab.name == "first") {
          this.tab1 = true;
          this.tab2 = false;
          this.tab3 = false;

          if(this.secondDisable == 1){
            this.data_two = this.dataList
          }
          if(this.secondDisable == 2){
            this.data_three = this.dataList
          }

          this.secondDisable = 0
          this.option = option  //换option
          this.dataList = 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.dataList
          }
          if(this.secondDisable == 2){
            this.data_three = this.dataList
          }

          this.secondDisable = 1
          this.option = optionAdd
          this.dataList = 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.dataList
          }
          if(this.secondDisable == 1){
            this.data_two = this.dataList
          }

          this.secondDisable = 2
          this.option = optionReturn
          this.dataList = this.data_three
        }
      },
      getProjectDetail(){
        if(this.id){
          projectDetail(this.id,"4,5,7,8").then(res =>{
            this.form = res.data.data;
            this.configuration.dicData   = res.data.data.corpName
            if(res.data.data.itemList){
              this.loading = true;
              this.allDataList = res.data.data.itemList;

              this.data_one=this.allDataList.filter(item=>item.projectType === 0)
              this.data_two=this.allDataList.filter(item=>item.projectType === 1)
              this.data_three=this.allDataList.filter(item=>item.projectType === 2)

              this.dataList = this.data_one

              this.activeName =  "first"
              this.tab1 = true;
              this.tab2 = false;
              this.tab3 = false;
              this.option = option
              this.secondDisable = 0

              this.loading = false;
            }
            if(res.data.data.filesList){
              this.upLoadData = res.data.data.filesList
            }
          })
        }
      },
      //结算
      beforeCloseAccount(row){
        this.aaccount = row;
        this.accountDialog = true;
      },
      closeAccount(form){
        this.$refs[form].validate((valid) => {
          if(valid){
            this.$confirm("确认结算此明细?", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              updateItemStatus(this.aaccount.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();
                }
              })
            });
          }
        })
      },
      //取消结算
      callAccount(row,index){
        this.$confirm("确认取消结算此明细?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          updateItemStatus(row.id,6).then(res =>{
            if(res.data.success){
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.getProjectDetail();
            }
          })
        });
      },
      //返回列表
      backToList(){
        this.$emit("goBack");
      },

      serviceConfirm(list){
        list.forEach((item)=>{
          const params = {
            strStatus:"录入",
            pname:item.cname,
            remarks:item.remarks,
            price:item.price,
            unit:item.unit,
            frequency:item.rate,
            projectType:this.secondDisable,
            status:this.secondDisable === 1?7:8
          }
          this.$refs.crud.rowCellAdd(params);
        })
        this.serviceDialog = false
      },
      choce(){
        this.serviceDialog = false
      },
      //新增 修改
      editMainProject(){
        if(this.secondDisable == 0){
          this.dataList = this.data_one
        }
        if(this.secondDisable == 1){
          this.dataList = this.data_two
        }
        if(this.secondDisable == 2){
          this.dataList = this.data_three
        }
        this.allDataList = []
        this.allDataList.push(...this.data_one,...this.data_two,...this.data_three)

        for (let i = 0; i < this.allDataList.length; i++) {
          if(this.allDataList[i].serviceCharge === (null || "")){
            return this.$message.error(`请输入明细列表服务费必填项`);
          }
          if(this.allDataList[i].matMoney === (null || "")){
            return this.$message.error(`请输入明细列表代垫费必填项`);
          }

          if(this.allDataList[i].userid === (null || "")){
            return this.$message.error(`请输入明细列表承做人必填项`);
          }
          if(this.allDataList[i].deptid === (null || "")){
            return this.$message.error(`请输入明细列表任务部门必填项`);
          }

          // if(this.allDataList[i].projectType === 2){
          //   this.allDataList[i].serviceCharge = -this.allDataList[i].serviceCharge
          //   this.allDataList[i].matMoney = -this.allDataList[i].matMoney
          // }

        }

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

        editMianProject(params).then(res =>{
          if(res.data.success){
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.getProjectDetail()
          }
        })
      },
      searchReset() {
        console.log('1')
      },
      selectionChange(row) {
        this.selectList = row
      },
      currentChange() {
        console.log('1')
      },
      sizeChange() {
        console.log('1')
      },
      refreshChange() {
        console.log('1')
      },
      rowCell(row, index) {
        this.$refs.crud.rowCell(row, index);
        // row.$cellEdit = !row.$cellEdit
      },
      rowUpdate(row, index, done, loading) {
        done(row);
      },
      rowDel(row,index){
        this.$confirm("确定将此明细删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.dataList.splice(index,1)
        });
      },
      //上传文件保存
      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=>{
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.bankOfDepositData.splice(index, 1);
            })
          }else {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.bankOfDepositData.splice(index, 1);
          }
        })
      },
    }
  }
</script>

<style scoped  lang="scss">
  .receipt-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;
  }
  .receipt-back {
    cursor: pointer;
    line-height: 62px;
    font-size: 16px;
    color: #323233;
    font-weight: 400;
  }
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
  .add-customer-btn {
    position: fixed;
    right: 12px;
    top: 47px;
  }
  .landConFrom-input{
    display:flex;
    justify-content:center;
  }
  ::v-deep .el-form-item__content{
    line-height: 32px;
  }
</style>
