<template>
  <div class="borderless">
    <div class="main-head">
      <div class="main-back">
        <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                   @click="backToList">返回列表
        </el-button>
        <el-button type="success"
                   class="el-button--small-yh add-customer-btn-two"
                   @click.stop="addMainProject">复制新单
        </el-button>
        <el-button class="el-button--small-yh add-customer-btn" 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="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="form[item.prop]" size="small" type="datetime" :disabled="item.disabled?true:false" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss"/>
                <el-date-picker v-else-if="item.type === 'date'" style="width: 100%;" v-model="form[item.prop]" size="small" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"/>
                <el-select v-else-if="item.prop === 'paymentType'" 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>
                <selectComponent v-else-if="item.prop === 'corpId'" v-model="form[item.prop]" :configuration="configuration"/>
                <el-input type="textarea" v-else-if="(item.prop === 'remark')" v-model="form[item.prop]"   size="small" autocomplete="off" placeholder="请输入"></el-input>
                <el-input type="age" v-else-if="item.prop === 'debitAmount'" v-model="form[item.prop]"  @change="debitChange"  :disabled="item.disabled?true:false" size="small" autocomplete="off" placeholder="请输入">
                  <template   slot="append">元</template>
                </el-input>
                <el-input type="age" v-else v-model="form[item.prop]"  :disabled="item.disabled?true:false" size="small" value="0" autocomplete="off" placeholder="请输入">
                  <template v-if="item.prop === 'debitAmount'|| 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>
        <avue-crud
          ref="crud"
          :data="data"
          :option="optionTable"
          :page.sync="page"
          :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-scope="scope" slot="menuLeft">
            <el-button type="primary"
                       size="small"
                       icon="el-icon-plus"
                       @click="serviceDialog = true">录入明细
            </el-button>
            <el-button type="info"
                       size="small"
                       @click.stop="beforePleaseCheck">请 核
            </el-button>
          </template>
          <template slot="menuRight">
            <el-button
              size="small"
              type="info"
              @click.stop="openReport()"
            >导出报表
            </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="userid" slot-scope="{row,index}">
            <span v-if="row.$cellEdit" style="float: left;color: #F56C6C;">*</span>
            <span style="margin-left: 12px;padding-top: 2px">{{ row.userName }}</span>
            <el-button v-if="row.$cellEdit" type="text" size="mini" style="float: right" @click="selectUser(row)">选择</el-button>
          </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"
      :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>
  </div>
</template>

<script>
  import option from "./configuration/detailsPage.json";
  import { projectDetail,editMianProject,updateItemStatus,getSysNo } 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 { getDictionary } from "@/api/system/dictbiz";
  // 当前登录人
  import { getUserInfo } from "@/api/system/user";
  //用户组件
  import userOption from "./configuration/userList.json";
  import { getList } from "@/api/system/user";
  import { getDeptLazyTree} from "@/api/system/dept";

  //上传附件删除
  import { corpsbank } from "@/api/basicData/configuration"

  export default {
    data() {
      return {
        id:'',
        loading: false,
        form:{},
        optionFrom:{},
        data: [],
        crudSelection:[],
        deptDicData:[],//任务部门数据
        serviceDialog:false,//服务导入窗口
        userDialog:false,//用户导入窗口
        //客户组件配置控制
        configuration:{
          multipleChoices:false,
          multiple:false,
          disabled:false,
          searchShow:false,
          collapseTags:false,
          placeholder:'请点击右边按钮选择',
          dicData:[]
        },
        page: {
          currentPage: 1,
          total: 0,
          pageSize: 10
        },
        detailsSelect: {},
        paymentTerm:[],
        //顶部from数据
        basicData: {
          column: [
            {
              label: '系统编号',
              prop: 'sysNo',
              disabled: true,
              rules: [
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            }, {
              label: '项目编码',
              prop: 'code',
              rules: [
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            }, {
              label: '项目名称',
              prop: 'cname',
              rules: [
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            }, {
              label: '客户名称',
              prop: 'corpId',
            },{
              label: '合同金额',
              prop: 'debitAmount',
              rules: [
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: ' ',
                  trigger: 'blur'
                },
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '首付金额',
              prop: 'advanceAmount',
              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,
              rules: [
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '未收金额',
              prop: 'balanceAmount',
              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',
            }, {
              label: '承揽人',
              prop: 'salesName',
            },
            {
              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',
              type:'select',
              dataType: "number",
              width: 120,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=affair_payment_term",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
            },
            {
              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',
            },
            {
              label: '备注',
              span: 24,
              prop: 'remark'
            }
          ],
        },
        optionTable: option,
        //上传文件
        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
        },
      };
    },
    created() {
      // 表格行编辑 输入框change事件
      //单价
      this.optionTable.column[5].change = function (val) {
        val.row.amount = val.row.quantity*val.value;
      }
      //数量
      this.optionTable.column[7].change = function (val) {
        val.row.amount = val.row.price*val.value;
      }

      this.$set(this.form,"debitAmount",0)
      this.$set(this.form,"advanceAmount",0)
      this.$set(this.form,"settlmentAmount",0)
      this.$set(this.form,"balanceAmount",0)
      this.id = BigInt(this.$route.query.id);//字符串转数字  超长用BigInt
      this.getProjectDetail();
      const params = {
        code : "affair_payment_term"
      }
      getDictionary(params).then(res =>{
        this.paymentTerm = res.data.data;
      })
    },
    mounted() {

    },
    methods: {
      //查询明细
      getProjectDetail(pleaseCheck){
        if(this.id){
          projectDetail(this.id,"0,1,2,3,4,5").then(res =>{
            this.form = res.data.data;
            this.configuration.dicData = res.data.data.corpName;
            if(res.data.data.filesList){
              this.upLoadData = res.data.data.filesList
            }
            if(res.data.data.itemList){
              this.data = res.data.data.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
                  }
                })
              }
              if(pleaseCheck === 10086){
                this.pleaseCheck();
              }
            }else{
              this.data = [];
            }
          })
        }else{
          getSysNo().then(res =>{
            this.$set(this.form,"sysNo", res.data.data)
            let date = new Date();
            let strDate = date.getFullYear() + "-" + date.getMonth() + 1 + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
            this.$set(this.form,"createTime",strDate)
          });
          getUserInfo().then(res =>{
            this.$set(this.form,"createUserName", res.data.data.name)
          })
        }
      },
      //删除列表后面的删除按钮触发触发(row, index, done)
      rowDel(row, index, done) {
        this.$confirm("确定将此明细删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.data.splice(index,0)
          // 数据回调进行刷新
          done(row);
        });
      },
      // 合同金额
      debitChange(val){
        if(val){
          if(!this.form.settlmentAmount){
            this.$set(this.form,"balanceAmount",val)
          }
        }
      },
      //点击修改或保存时触发
      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);
      },
      //新单
      addMainProject(){
        this.$confirm("需先将此单据保存", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=>{
          this.editMainProject(10010);
        })
      },
      //请核
      beforePleaseCheck(){
        if(this.crudSelection.length!=0){
          let resultUserName = [];
          let result = [];
          this.crudSelection.forEach(item=>{
            // 新录入状态下  才可提交审核
            item.createUserName ? resultUserName.push(true) : resultUserName.push(false) //如果没有创建人并且为新录入  提示保存
            item.strStatus === "录入" ? result.push(true) : result.push(false) //判断所有的是否为录入状态
          })
          if(resultUserName.findIndex(item => item != true) == -1){
            // 如果数组内有一个 为false  则为false
            if(result.findIndex(item => item != true) == -1){
              this.editMainProject(10086);
            }else{
              this.$message({
                type: "error",
                message: "请核数据中存在已请核数据!"
              });
              return
            }
          }else{
            this.$confirm("列表内存在新录入数据,是否先保存此数据?", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              this.editMainProject();
              return
            })
          }
        }else{
          this.$message({
            type: "error",
            message: "请先选择一条数据!"
          });
        }
      },
      pleaseCheck(){
        this.crudSelection.forEach(item =>{
          updateItemStatus(this.data[item.$index].id,1).then(res =>{
            if(res.data.success){
              this.$message({
                type: "success",
                message: "请核成功!"
              });
              //刷新列表
              this.loading = true;
              projectDetail(this.id,"0,1,2,3,4,5").then(res =>{
                if(res.data.data.itemList){
                  this.data = res.data.data.itemList;
                }else{
                  this.data = [];
                }
                this.loading = false;
              })
            }
          })
        })
      },
      //新增 修改
      editMainProject(pleaseCheck){
        this.$refs["form"].validate((valid) => {
          //校验明细列表
          let valids = true;
          if(this.data.length !=0){
            this.data.forEach((item) =>{
              if((item.userid ==""  || !item.deptid || !item.amount) && valids){
                this.$message({
                  type: "warning",
                  message: "请检查明细列表第 "+(item.$index +1 )+" 行必填项"
                });
                valids = false;
              }
            })
          }
          if(valid && valids){
            const params = {
              ...this.form,
              itemList:this.data,
              filesList:this.upLoadData
            }
            editMianProject(params).then(res =>{
              if(pleaseCheck !== 10086 && pleaseCheck !== 10010){
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                this.getProjectDetail()
              }else if(pleaseCheck === 10010){  //新单
                this.$router.push({
                  path: "/mainItems_detailsPage",
                  query: {id: ''},
                });
                this.form = {}
                this.data = []
                this.upLoadData = []
                this.id = ''
              }else if(pleaseCheck === 10086){
                this.getProjectDetail(pleaseCheck)
              }
            })
          }
        })
      },
      //返回主营项目列表
      backToList(){
        this.$router.$avueRouter.closeTag();
        this.$router.push({
          path: '/workManagement/main-items/list',
          query: {}
        });
      },
      //上传文件保存
      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,
              frequency:item.rate,
            }
            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
         }
      }
    },
  };
</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;
  }
  .main-back {
    cursor: pointer;
    line-height: 62px;
    font-size: 16px;
    color: #323233;
    font-weight: 400;
  }
  .avue-tree {
    overflow: hidden;
    max-height: 660px;
  }
  .add-customer-btn-two {
    position: fixed;
    right: 150px;
    top: 115px;
  }
  .add-customer-btn {
    position: fixed;
    right: 36px;
    top: 115px;
  }
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
</style>
