<template>
  <div id="ProssBox">
    <!-- 查询 -->
    <div class="searchBox">
      <el-row :gutter="10">
        <el-col :span="16">
          <div>
            <span>项目名称：</span>
            <el-input placeholder="请输入项目名称" size="mini" v-model="boGroup" style="width: 204px" clearable>
            </el-input>
            <el-button style="margin-left:10px" type="primary" size="mini" @click="getlistdata()">查询</el-button>
            <!-- <el-button type="primary" size="mini" @click="newopen()">新建项目</el-button>
            <el-button type="primary" size="mini" @click="deleteProject()">删除项目</el-button> -->
            <!-- <el-button type="primary" size="mini" @click="syncProject()">项目同步</el-button>
            <el-button type="primary" size="mini" @click="syncContract()">合同同步</el-button> -->
            <el-button type="primary" size="mini" @click="initialPosition()">初始位置</el-button>
            <el-button type="primary" size="mini" @click="processConfig()">工艺配置</el-button>
            <el-button type="primary" size="mini" @click="orgprj()">区域绑定</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 项目详情 -->
    <div class="projectBox">
      <el-row :gutter="20" style=" height:100%;margin:0px">
        <el-col :span="12" style=" height:100%;">
          <!-- 主项目 -->
          <div class="grid-content bg-purple">
            <tf-table ref="prjTb" highlight-current-row :data="tableData" @selection-change="handleSelectionChange" @row-click="details">
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column prop="name" label="项目名称（项目编号）" style="width: 100%">
                <template slot-scope="scope">{{ scope.row.name }}（{{ scope.row.code }}）</template>
              </el-table-column>
            </tf-table>
            <!-- <el-table ref="multipleTable"  highlight-current-row
            :stripe="true"
            :data="tableData" 
            tooltip-effect="dark" 
            height="100%" 
            align="center" 
            style="width: 100%" 
            :header-cell-style="headerStyle"
            @selection-change="handleSelectionChange" 
            @row-click="details">
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column prop="name" label="项目名称（项目编号）" style="width: 100%">
                <template slot-scope="scope">{{ scope.row.name }}（{{ scope.row.code }}）</template>
              </el-table-column>
            </el-table> -->
          </div>
        </el-col>
        <el-col :span="12" style="height: 100%">
          <!-- 项目详情 -->
          <div class="grid-content test-5" style="height: calc(100% - 98px);">
            <span style="display:block;margin-bottom:10px;">资源配置：</span>
            <el-tree style="height:calc(100% - 30px);border:1px solid #dbe4ff;overflow:auto;" v-if="data" :data="data" show-checkbox default-expand-all node-key="id" ref="tree" highlight-current :props="defaultProps" :default-checked-keys="treeSelectKeys" @node-contextmenu="setServeIndex">
            </el-tree>
          </div>
          <div class="buttons">
            <el-checkbox v-model="isShowServeIndex" label="显示服务序号" border size="mini" :disabled="data.length==0" @change="showServeIndex()"></el-checkbox>
            <el-button type="primary" @click="getCheckedKeys" size="mini">资源配置保存</el-button>
            <!-- <el-button @click="setCheckedKeys">通过 key 设置</el-button> -->
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog title="新增项目" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="项目编码" :label-width="formLabelWidth" :rules="[
     { required: true, message: '请输入项目编码', trigger: 'blur' },
    ]">
          <el-input v-model="form.code" placeholder="请输入项目编码" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="项目全称" :label-width="formLabelWidth" :rules="[
     { required: true, message: '请输入项目全称', trigger: 'blur' },
    ]">
          <el-input v-model="form.name" autocomplete="off" placeholder="请输入项目全称"></el-input>
        </el-form-item>

        <el-form-item label="工程范围" :label-width="formLabelWidth">
          <el-input v-model="form.gcfw" autocomplete="off" placeholder="请输入工程范围"></el-input>
        </el-form-item>
        <el-form-item label="建设单位" :label-width="formLabelWidth">
          <el-input v-model="form.unit" autocomplete="off" placeholder="请输入建设单位"></el-input>
        </el-form-item>
        <el-form-item label="项目投资" :label-width="formLabelWidth">
          <el-input v-model="form.xmtz" autocomplete="off" placeholder="请输入项目投资"></el-input>
        </el-form-item>
        <el-form-item label="项目工期" :label-width="formLabelWidth">
          <el-input v-model="form.xmzq" autocomplete="off" placeholder="请输入项目工期"></el-input>
        </el-form-item>
        <el-form-item label="项目介绍" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="form.xmjs" autocomplete="off" placeholder="请输入项目介绍" :autosize="{ minRows: 5}"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addProject() ">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="初始位置" :visible.sync="dialogFormVisible2">
      <el-form :model="form2">
        <el-form-item label="经度" :label-width="formLabelWidth" :rules="[
     { required: true, message: '请输入经度', trigger: 'blur' },
    ]">
          <el-input v-model="form2.lon" placeholder="请输入经度" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="纬度" :label-width="formLabelWidth" :rules="[
     { required: true, message: '请输入纬度', trigger: 'blur' },
    ]">
          <el-input v-model="form2.lat" autocomplete="off" placeholder="请输入项目全称"></el-input>
        </el-form-item>
        <el-form-item label="相机高度" :label-width="formLabelWidth" :rules="[
     { required: true, message: '请输入相机高度', trigger: 'blur' },
    ]">
          <el-input v-model="form2.height" autocomplete="off" placeholder="请输入相机高度"></el-input>
        </el-form-item>
        <el-form-item label="空间数据库" :label-width="formLabelWidth">
          <el-input v-model="form2.dataUser" autocomplete="off" placeholder="请输入空间数据库"></el-input>
        </el-form-item>
        <el-form-item label="坐标参考系" :label-width="formLabelWidth">
          <el-input v-model="form2.wkid" autocomplete="off" placeholder="请输入坐标参考系"></el-input>
        </el-form-item>
        <el-form-item label="PBS编码模板" :label-width="formLabelWidth">
          <el-input v-model="form2.pbsModel" autocomplete="off" placeholder="请输入PBS编码模板"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="putInitial() ">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="工艺配置" :visible.sync="dialogFormVisible3" width="25%">
      <el-form :model="form3">
        <el-form-item label="项目名称：" :label-width="formLabelWidth">
          <el-input v-model="form3.name" placeholder="请输入项目全称" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="工艺分组：" :label-width="formLabelWidth">
          <el-select v-model="processValue" placeholder="请选择" style="width:100%" @change="processChange($event)">
            <el-option v-for="item in processOptions" :key="item.id" :label="item.value" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择工艺：" :label-width="formLabelWidth" v-show="checkItems.length!=0">
          <el-checkbox-group v-model="checkedConfig">
            <el-checkbox v-for="item in checkItems" :key="item.id" :label="item.id">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeProcessConfig()">取 消</el-button>
        <el-button @click="submitConfig()" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="服务顺序配置" :visible.sync="dialogFormVisible4" width="25%">
      <el-form :model="form4">
        <el-form-item label="服务名称：" :label-width="formLabelWidth">
          <el-input v-model="form4.name" placeholder="请输入项目全称" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="服务序号：" :label-width="formLabelWidth" :rules="[
     { required: true, message: '请输入服务序号', trigger: 'blur' },
    ]">
          <el-input v-model="form4.sort" placeholder="请输入序号" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分组名称：" :label-width="formLabelWidth" :rules="[
     { required: true, message: '请输入分组名称', trigger: 'blur' },
    ]">
          <el-input v-model.trim="form4.groupname" placeholder="请输入分组名称" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible4 = false">取 消</el-button>
        <el-button @click="setServiceSort()" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="区域绑定" :visible.sync="dialogOrgFormVisible" width="25%">
      <el-form :model="formOrg">
        <el-form-item label="区域总部：" :label-width="formLabelWidth">
          <el-select v-model="formOrg.orgId" placeholder="请选择" style="width:100%">
            <el-option v-for="item in orgOptions" :key="item.id" :label="item.orgName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogOrgFormVisible = false">取 消</el-button>
        <el-button @click="setOrgPrj()" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import axios from 'axios'
import {
  postPrjSubList_api,
  syncProject_api,
  syncContract_api,
  putPrjList_api,
  deleteProject_api,
  getBaseCodePage_api,
  batchByTdIds_api,
  updateSort_api,
  AreacompanyPage_api,
  BasePrjsourceListSourceById_api,
  BasePrjsourceUpdate_api,
  getOrglist_api,
  getOrgPrj_api
} from '@/api/APIs'
export default {
  name: 'ProjectResource',
  data() {
    return {
      boGroup: '',
      tableData: [],
      headerStyle: {
        textAlign: 'center'
      },
      multipleSelection: [],
      dialogFormVisible: false,
      dialogFormVisible2: false,
      data: [],
      treeData: [],
      defaultProps: {
        children: 'funs',
        label: 'name'
      },
      detailsurl: '/base/prjsource/listSourceById', //详情同飞数据库
      detailsPutUrl: '/base/prjsource/update', //详情更改同飞数据库
      treeSelectKeys: [],
      treeClickRow: null,
      ids: '', //详情id
      // 新增
      form: {
        code: '',
        gcfw: '',
        name: '',
        unit: '',
        xmtz: '',
        xmzq: '',
        xmjs: ''
      },
      form2: {
        lon: '',
        id: '',
        lat: '',
        height: '',
        dataUser:'',
        wkid:'',
        pbsModel:null
      },
      formLabelWidth: '120px',
      dialogFormVisible3: false,
      dialogOrgFormVisible:false,
      form3: {
        name: ''
      },
      processValue: '',
      processOptions: [],
      checkItems: [],
      checkedConfig: [],
      maps: ['maps', 'img', 'theme'],
      isShowServeIndex: false,
      dialogFormVisible4: false,
      form4: {
        name: '',
        sort: '',
        groupname: '',
        id: ''
      },
      formOrg:{
        orgId:''
      },
      orgOptions:[]
    }
  },

  methods: {
    newopen() {
      this.dialogFormVisible = true
    },
    // 获取表格
    async getlistdata() {
      let params = {
        name: this.boGroup,
        current: 1,
        size: 10000
      }
      let res = await AreacompanyPage_api(params)
      let { code, result } = res
      if (code === 1) {
        this.tableData = result.records
        this.$nextTick(()=>{
          if(this.tableData.length>0){//默认选择第一行
            this.details(this.tableData[0]);
            console.log(this.$refs.prjTb);
            this.$refs.prjTb.$refs.table.setCurrentRow(this.tableData[0]);
          }
          
        })
      }
    },
    //更改详情
    async getCheckedKeys() {
      console.log(this.$refs.tree.getCheckedKeys())
      let data = {
        prjId: this.ids.toString(),
        sourceIds: this.$refs.tree.getCheckedKeys().join(','),
        type: 'Source'
      }
      let res = await BasePrjsourceUpdate_api(data)
      let { code, message } = res
      if (code == 1) {
        this.$message({
          message: '资源配置成功！',
          type: 'success'
        })
      } else {
        this.$message.error(message)
      }
    },
    // 获取详情
    async details(row) {
      this.treeClickRow = row
      this.treeSelectKeys = []
      this.ids = row.id
      let params = {
        id: row.id,
        current: 1,
        size: 10000
      }
      let res = await BasePrjsourceListSourceById_api(params)
      let { code, result } = res
      console.log({ 资源: result })
      if (code === 1) {
        this.treeData = result
        this.data = result.map((item) => {
          // console.log("item", item);
          let selectData = item.funs.filter((dt) => dt.isExists == 'true')
          let drs = selectData.map((dt) => dt.id)
          this.treeSelectKeys.push(...drs)
          if (this.isShowServeIndex) {
            return {
              ...item,
              funs: this.fileName(item, this.isShowServeIndex)
            }
          } else {
            return {
              ...item
              // children: item.funs,
            }
          }
        })
      }
    },
    // 新增项目
    addProject() {
      let data = {
        code: this.form.code,
        gcfw: this.form.gcfw,
        name: this.form.name,
        unit: this.form.unit,
        xmtz: this.form.xmtz,
        xmzq: this.form.xmzq,
        xmjs: this.form.xmjs
      }
      postPrjSubList_api(data)
        .then((res) => {
          console.log(res.data, '成功数据')
          let { code, message } = res

          if (code == 1) {
            this.$message({
              message: '新增成功！',
              type: 'success'
            })
            this.dialogFormVisible = false
            this.getlistdata()
          } else {
            this.$message.error(message)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 项目同步
    syncProject() {
      this.$message({
        message: '项目同步时间较长，请稍后查看！',
        type: 'warning'
      })
      syncProject_api({})
        .then((res) => {
          console.log(res.data, '成功数据')
          let { code, result } = res
          if (code === 1) {
            this.$message({
              message: '项目同步成功！',
              type: 'success'
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //  勾选框
    handleSelectionChange(val) {
      debugger;
      if (val.length != 0) {
        this.form2.id = val[0].id
        this.multipleSelection = val
      } else {
        this.multipleSelection = []
      }
    },
    // 初始位置
    initialPosition() {
      if (this.multipleSelection.length == 1) {
        this.dialogFormVisible2 = true
        const china = {
          lon: 116.435314,
          lat: 40.960521,
          height: 10000000.0
        }
        const project=this.multipleSelection[0];
        const position = project['geo_info']
        if (!position) {
          this.form2.lon = china.lon
          this.form2.lat = china.lat
          this.form2.height = china.height
        } else if (position) {
          try {
            const initposition = JSON.parse(position)
            this.form2.lon = initposition.lon
            this.form2.lat = initposition.lat
            this.form2.height = initposition.height
          } catch (error) {
            this.form2.lon = china.lon
            this.form2.lat = china.lat
            this.form2.height = china.height
          }
          this.form2.dataUser=project.dataUser;
          this.form2.wkid=project.wkid;
          this.form2.pbsModel=project.pbsModel;
        }
      } else {
        this.$message('请勾选一个项目！')
      }
    },
    //更改初始位置
    putInitial() {
      const lon = this.form2.lon
      const lat = this.form2.lat
      const height = this.form2.height
      if (isNaN(lon) || isNaN(lat) || isNaN(height)) {
        this.$message('请填写坐标信息')
        return
      }
      const data = {
        id: this.form2.id,
        geo_info: JSON.stringify({
          lon: lon,
          lat: lat,
          height: height
        }),
        dataUser:this.form2.dataUser,
        wkid:this.form2.wkid,
        pbsModel:this.form2.pbsModel
      }
      putPrjList_api(data)
        .then((res) => {
          const e = res
          if (e.code !== -1) {
            this.dialogFormVisible2 = false
            this.$message.success('保存成功')
          } else {
            this.$message.error('保存失败')
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //合同同步
    syncContract() {
      this.$message({
        message: '同步进行中，时间较长请稍后查看',
        type: 'warning'
      })
      syncContract_api({})
        .then((res) => {
          const e = res
          if (e.code === -1) {
            this.$message.error('合同同步失败')
          } else {
            this.$message.success('合同同步成功')
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //删除项目
    deleteProject() {
      if (this.multipleSelection.length < 1) {
        this.$message('请选择至少一位项目进行删除！')
        return
      }
      let deleteInfo = { ids: [] }
      for (var id in this.multipleSelection) {
        deleteInfo.ids.push(id)
      }
      deleteProject_api(deleteInfo)
        .then((res) => {
          const results = res
          if (results.code != 1) {
            console.error(results.message)
          } else {
            this.$message.success('项目删除成功')
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //工艺配置
    processConfig() {
      if (this.multipleSelection.length == 0) {
        this.$message('请选择一行数据进行工艺配置')
        return
      }
      if (this.multipleSelection.length > 1) {
        this.$message('最多选择一行数据进行工艺配置')
        return
      }
      this.processOptions = []
      this.checkedConfig = []
      let datas = this.multipleSelection[0]
      this.form3.name = datas.name
      //分组查询
      let data2 = {
        key: 'td_tech_group',
        ulevel: '2',
        size: 999
      }
      getBaseCodePage_api(data2)
        .then((res) => {
          const results = res
          this.processOptions = results.result.records
          this.dialogFormVisible3 = true
        })
        .catch((err) => {
          console.log(err)
        })
    },
    processChange(data) {
      this.checkItems = []
      this.checkedConfig = []
      this.$PortApi
        .TdtechPage_api({ tdGroupId: data })
        .then((res) => {
          const results = res.data
          if (results.result.records.length == 0) {
            return
          }
          results.result.records.forEach((item) => {
            this.checkItems.push({ name: item.name, id: item.id })
          })
        })
        .catch((err) => {
          console.log(err)
        })
    },
    /**
     * 项目绑定区域
     */
    orgprj(){
      if (this.multipleSelection.length == 0) {
        this.$message('请选择一行数据进行区域绑定')
        return
      }
      if (this.multipleSelection.length > 1) {
        this.$message('最多选择一行数据进行区域绑定')
        return
      }
      this.processOptions = []
      this.checkedConfig = []
      let datas = this.multipleSelection[0]
     
      getOrglist_api({})
        .then((res) => {
          const results = res
          this.orgOptions = results.result.records
          this.dialogOrgFormVisible = true
        })
        .catch((err) => {
          console.log(err)
        })
    },
    setOrgPrj(){
      const prjid=this.form2.id;
      const orgid=this.formOrg.orgId;
      const data={
        prjId: prjid,
        orgId: orgid
      }
      getOrgPrj_api(data).then(result=>{
        if(result.code===1){
          this.$message.success('区域绑定成功');
          this.dialogOrgFormVisible=false;
        }
      }).catch((err) => {
        this.$message.error('区域绑定失败');
        console.log(err)
      })
    },
    submitConfig() {
      let checkString = []
      this.checkedConfig.forEach((item) => {
        checkString.push(item)
      })
      let setData = {
        prjId: this.multipleSelection[0].id,
        tdIds: checkString.join(',')
      }
      batchByTdIds_api(setData)
        .then((res) => {
          const results = res
          if (results.code != 1) {
            this.$message.error('工艺配置失败')
          } else {
            this.$message.success('工艺配置成功')
            this.closeProcessConfig()
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    closeProcessConfig() {
      this.dialogFormVisible3 = false
      this.processOptions = []
      this.checkedConfig = []
    },
    showServeIndex() {
      let that = this
      if (this.isShowServeIndex) {
        this.data = this.treeData.map((item) => {
          return {
            ...item,
            funs: this.fileName(item, this.isShowServeIndex)
          }
        })
      } else {
        this.data = this.treeData.map((item) => {
          return {
            ...item,
            funs: this.fileName(item, this.isShowServeIndex)
          }
        })
      }
    },
    fileName(item, checked) {
      let node = item.funs
      node.forEach((element) => {
        if (this.maps.indexOf(item.code) > -1) {
          if (checked) {
            const sort = element.sort ? element.sort : '/'
            element.name = element.name + ' ( ' + sort + ' ) '
          } else {
            element.name = element.name.substring(0, element.name.indexOf(' ( '))
          }
        }
      })
      return node
    },
    setServeIndex(e, data, node) {
      if (data !== null && this.maps.indexOf(node.parent.data.code) > -1) {
        this.form4.name = data.name
        this.form4.sort = data.sort
        this.form4.groupname = data.sourceGroup
        this.form4.id = data.id
        this.dialogFormVisible4 = true
      }
    },
    setServiceSort() {
      const sort = this.form4.sort
      const groupName = this.form4.groupname
      const prjId = this.treeClickRow.id
      const sourceId = this.form4.id
      if (isNaN(sort)) {
        this.$message('请填写序号')
        return
      }
      const data = [
        {
          prjId: prjId,
          sort: sort,
          sourceGroup: groupName,
          sourceId: sourceId
        }
      ]
      axios.defaults.baseURL = '/api'
      axios({
        headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        },
        method: 'post',
        url: '/tofly-base/prjsource/updateSort',
        data: JSON.stringify(data)
      })
        .then((res) => {
          const e = res.data
          if (e.code !== -1) {
            this.dialogFormVisible4 = false
            this.$message.success('保存成功')
          } else {
            this.$message.error('保存失败')
          }
        })
        .catch((err) => {
          console.log(err)
        })
    }
  },
  created() {
    this.getlistdata()
  }
}
</script>
<style lang="scss" scoped>
#ProssBox {
  width: 100%;
  height: 100%;
  position: absolute;
  .searchBox {
    padding: 10px;
  }
  .projectBox {
    height: calc(100% - 48px);
    .el-row {
      height: 100%;
    }
  }
}
.buttons {
  margin: 10px 0 0 0;
  .el-button {
    margin-left: 10px;
  }
}
.bg-purple {
  border: 1px solid #dbe4ff;
  padding: 10px;
  overflow-y: auto;
  height: calc(100% - 60px);
}
</style>
