<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 class="el-button--small-yh add-customer-btn" type="primary"
        >保存
        </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'" style="width: 100%;" v-model="form[item.prop]" size="small" type="datetime" 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.type === 'select'" style="width: 100%" size="small" placeholder="请选择" clearable filterable></el-select>
                <selectComponent v-else-if="item.prop === 'corpId'" v-model="form[item.prop]" :configuration="configuration"/>
                <el-input type="age" v-else v-model="form[item.prop]" size="small" autocomplete="off" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </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"
          @size-change="sizeChange"
          @current-change="currentChange"
          @selection-change="selectionChange"
          @search-change="searchChange"
          @refresh-change="refreshChange"
          @on-load="getList"
          @saveColumn="saveColumn"
        >
          <template slot="menuLeft">
            <el-button type="success"
                       size="small"
                       icon="el-icon-plus"
                       plain
                       @click="serviceDialog = true">新增明细
            </el-button>
            <el-button type="success"
                       size="small"
                       icon="el-icon-plus"
                       plain
                       @click="">新 单
            </el-button>
            <el-button type="info"
                       size="small"
                       plain
                       @click="">请 核
            </el-button>
          </template>
          <template slot="menuRight">
            <el-button type="primary"
                       size="small"
                       icon="el-icon-arrow-right"
                       plain
                       @click="">导 出
            </el-button>
            <el-button type="primary"
                       size="small"
                       plain
                       @click="">打 印
            </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 style="float: left;padding-top: 2px">{{ row.userId }}</span>
            <el-button 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";
  //上传文件json
  import upLoadOption from "../../exportTrade/purchaseContract/config/uploadList.json"
  //服务列表接口
  import {getServiceProjectList,getServiceTypeTree,} from "@/api/workManagement/serviceProject";
  import serviceOption from "./configuration/serviceDialogList.json";
  //任务部门树接口
  import {getLazyList} from "@/api/system/dept";
  //用户组件
  import userOption from "./configuration/userList.json";
  import { getList } from "@/api/system/user";
  import { getDeptLazyTree} from "@/api/system/dept";

  export default {
    data() {
      return {
        loading: false,
        form:{},
        optionFrom:{},
        data: [
          {
            deptId:'',
            userId:''
          }
        ],
        deptDicData:[],//任务部门数据
        serviceDialog:false,//服务导入窗口
        userDialog:false,//用户导入窗口
        //客户组件配置控制
        configuration:{
          multipleChoices:false,
          multiple:true,
          searchShow:true,
          collapseTags:true,
          placeholder:'请点击右边按钮选择',
          dicData:[]
        },
        page: {
          currentPage: 1,
          total: 0,
          pageSize: 10
        },
        detailsSelect: {},
        //顶部from数据
        basicData: {
          column: [
            {
              label: '系统编号',
              prop: 'sysNo',
              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]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
                  message: '请输入数字或小数，且小数位不超过两位',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '首付金额',
              prop: 'advanceAmount',
              rules: [
                {
                  pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
                  message: '请输入数字或小数，且小数位不超过两位',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '未收金额',
              prop: 'balanceAmount',
              rules: [
                {
                  pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
                  message: '请输入数字或小数，且小数位不超过两位',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '已收金额',
              prop: 'settlmentAmount',
              disabled:true,
              rules: [
                {
                  pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
                  message: '请输入数字或小数，且小数位不超过两位',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '责任人',
              prop: 'corpAttn',
            }, {
              label: '承揽人',
              prop: 'salesName',
            },
            {
              label: '制单人',
              prop: 'createUser',
            }, {
              label: '制单日期',
              prop: 'createTime',
              type: 'datetime'
            },
            {
              label: '电话',
              prop: 'corpTel',
            },
            {
              label: '收款方式',
              prop: 'paymentType',
              type:'select',
              dataType: "number",
              width: 120,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=payment_term",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
            },
            {
              label: '开始日期',
              prop: 'beginTime',
              type:'datetime',
            },
            {
              label: '结束日期',
              prop: 'endTime',
              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
        },
      };
    },
    mounted() {
    },
    methods: {
      //删除列表后面的删除按钮触发触发(row, index, done)
      rowDel(row, index, done) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          // 数据回调进行刷新
          done(row);
        });
      },
      //点击修改或保存时触发
      rowCellTwo(row,index){
        if(row.$cellEdit){
          setTimeout(() => {
            this.$message.success("保存成功");
          }, 1000);
        }else{
          this.$refs.crud.rowCell(row, index);
        }
      },
      //新增修改时保存触发
      rowSave(row, done, loading) {

      },
      getList() {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.page.total = 1;
        }, 1000);
      },
      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();
      },
      refreshChange() {
        this.page.currentPage = 1;
        this.getList();
      },
      saveColumn(row, column) {
        console.log(row, column);
      },
      //返回主营项目列表
      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=>{
              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)=>{
            item.prop1 = item.code;
            item.prop2 = item.name;
            item.prop4 = item.unit;
            item.prop3 = item.remarks;
            this.$refs.crud.rowCellAdd(item);
            this.$refs.crud.rowCell(item, this.optionFrom.length-1)
          })
        }
        this.serviceSelectList = []
        this.serviceDialog = false
      },
      //用户窗口事件
      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.optionFrom[this.detailsSelect].userId = this.userSelection[0].userId;
         }
      }
    },
  };
</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 {
    position: fixed;
    right: 36px;
    top: 115px;
  }
</style>
