<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :rules="queryRules" :inline="true" v-show="showSearch">
      <el-row>
        <el-form-item label="领料单位" prop="unitId">
          <el-select  v-model="queryParams.unitId" clearable @change="GetProData" style="width: 240px" placeholder="请选择">
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="领料工程" prop="proId">
          <el-select  v-model="queryParams.proId" clearable @change="GetUnitData" style="width: 240px" placeholder="请选择">
            <el-option
              v-for="item in proList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="协议号" prop="agreementCode">
          <el-input v-model="queryParams.agreementCode" disabled></el-input>
        </el-form-item>
        <el-form-item label="物品类型" prop="status">
          <el-cascader
            placeholder="请输入物品类型"
            :options="deviceTypeTree"
            :props="deviceTypeTreeProps"
            v-model="deviceType"
            @change="deviceTypeChange"
            ref="deviceTypeCascader"
            filterable></el-cascader>
        </el-form-item>
        <el-form-item label="领料人" prop="roleName">
          <el-input
            v-model="queryParams.leaseApplyInfo.leasePerson"
            placeholder="请输入领料人"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="领料人电话" prop="roleName">
          <el-input
            v-model="queryParams.leaseApplyInfo.phone"
            placeholder="请输入领料人电话"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="备注" prop="roleName">
          <el-input
            v-model="queryParams.leaseApplyInfo.remark"
            placeholder="请输入备注"
            clearable
            rows="1"
            type="textarea"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-row>
      <el-row>

      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >保存</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
        >领料管理</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="leaseApplyDetails" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="120" />
      <el-table-column label="类型名称" prop="typeCn" width="200" :show-overflow-tooltip="true"   />
      <el-table-column label="规格型号" prop="guigeCn" width="200" :show-overflow-tooltip="true" />
      <el-table-column label="计量单位" prop="unitCn" width="100" />
      <el-table-column label="预领数量" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <el-input
            v-model.number="scope.row.preNum"
            placeholder="请输入预领数量"
            type="number"
            clearable
            style="width: 100%"
            @keyup.enter.native="handleQuery"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.remark"
            placeholder="请输入备注"
            clearable
            style="width: 100%"
            @keyup.enter.native="handleQuery"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['system:role:edit']"-->
<!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete({...scope.row,index:scope.$index})"
          >删除</el-button>

        </template>
      </el-table-column>
    </el-table>




  </div>
</template>

<script>
import {  getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus, deptTreeSelect } from "@/api/system/role";
import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu";
import {
  getProData,
  getUnitData,
  getDeviceTypeTree,
  getAgreementInfoById,
  submitLeaseApply,
  getTaskDetail
} from '@/api/claimAndRefund/receive'

import { mapState } from 'vuex'
export default {
  name: "Role",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {

        types:2,

        unitId:null,
        proId:null,
        agreementId:null, //协议id
        agreementCode: null, //协议code
        companyId:'', //登录信息中取
        createBy: '', //用户名
        taskType: 29,
        taskStatus: 30,
        //领料人信息
        leaseApplyInfo:{
          leasePerson: '',
          phone: '',
          remark: ''
        },
        //领料详情集合
        leaseApplyDetails:[]
      },
      leaseApplyDetails:[],



      //领料详情单条模板
      leaseApplyDetailsItem:{
        createBy: null,
        companyId: null,
        status: 0,
        typeId: null, //  树结构第4级   规格id
        typeCn:'', //显示的设备类型
        guigeCn:'', //显示的设备规格
        unitCn:'', //显示的设备 单位
        remark: '', //单条备注
        preNum: 1, //预领数量
      },
      //
      queryRules:{
        unitId:[
          {
            required:true,message:'请选择来往单位',trigger:'change',type:'number'
          }
        ],
        proId:[
          {
            required:true,message:'请选择工程',trigger:'change',type:'number'
          }
        ]
      },
      unitList:[], //单位 集合
      proList:[], // 工程 集合
      deviceTypeTree: [], // 设备 树结构数据
      // 设备 树显示 配置
      deviceTypeTreeProps: {
        multiple:false,
        value:'id'
      },
      // 选中的设备类型
      deviceType: null,

      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.GetUnitData()

    this.GetProData()

    this.GetDeviceTypeTree()
    // this.getList();
    console.log('this.$route.query.taskId',this.$route.query.taskId)
    if(this.$route.query.taskId){
      this.GetTaskDetail(this.$route.query.taskId)
    }
  },
  computed:{
    ...mapState(['user'])
  },
  methods: {
    // 获取 来往单位 列表数据
    async GetUnitData(){
      const params = {
        id:this.queryParams.proId
      }
      const res = await getUnitData(params)
      this.unitList = res.data

      this.GetAgreementInfoById()
    },
    // 获取 工程名称 列表数据
    async GetProData(){
      const params = {
        id:this.queryParams.unitId
      }
      const res = await getProData(params)
      this.proList = res.data

      this.GetAgreementInfoById()
    },

    // 获取 设备树结构数据
    async GetDeviceTypeTree(){
      const params = {
        level:4
      }
      const res = await getDeviceTypeTree(params)
      this.deviceTypeTree = res.data

    },
    // 获取 协议id
    async GetAgreementInfoById(){
      if(this.queryParams.unitId && this.queryParams.proId){
        const params = {
          unitId: this.queryParams.unitId,
          projectId: this.queryParams.proId
        }
        const res = await getAgreementInfoById(params)
        if( !(res.data && res.data.agreementId) ){
          this.$message.error('当前单位和工程未上传');

          this.queryParams.unitId = null
          this.queryParams.proId = null
          this.GetUnitData()
          this.GetProData()
        }else{
          this.queryParams.agreementId = res.data.agreementId
          this.queryParams.agreementCode = res.data.agreementCode
        }
      }
    },

    // 获取 任务详情数据
    async GetTaskDetail(taskId){
      const res = await getTaskDetail({taskId})

      const data = res.rows[0]
      console.log('GetTaskDetail =================',data)

        // unitId:null,
        // proId:null,
        // agreementId:null, //协议id
        // agreementCode: null,

      this.queryParams.unitId = data.unitId
      this.queryParams.proId = data.projectId
      this.queryParams.leaseApplyInfo.phone = data.leaseApplyInfo.phone
      this.queryParams.leaseApplyInfo.leasePerson = data.leaseApplyInfo.leasePerson
      this.queryParams.agreementCode = data.agreementCode
      this.queryParams.leaseApplyInfo.remark = data.leaseApplyInfo.remark

      this.leaseApplyDetails = data.leaseApplyDetails.map(item => {
          return this.handelEchoData(item)
      })

    },
    //生成回显数据
    handelEchoData(item){
      const template = JSON.parse(JSON.stringify(this.leaseApplyDetailsItem))
      template.createBy = item.createBy
      template.companyId = item.companyId
      template.typeId = item.typeId
      template.unitCn = item.unitName
      template.typeCn = item.typeName
      template.guigeCn = item.typeModelName
      template.remark = item.remark
      template.preNum = item.preNum
      template.status = item.status

      return template
    },


    /** 查询角色列表 */
    async getList() {


    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then(response => {
        this.menuOptions = response.data;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus;
        return response;
      });
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then(response => {
        this.deptOptions = response.depts;
        return response;
      });
    },
    // 角色状态修改

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
        this.menuNodeAll = false,
        this.deptExpand = true,
        this.deptNodeAll = false,
        this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined
        };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.queryParams.leaseApplyDetails = selection
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },

    /** 保存按钮操作 */
     handleAdd() {
      this.$refs.queryForm.validate(async (valid) => {
          if(!valid){
            return false
          }else {
            if( this.queryParams.leaseApplyDetails.length == 0 ){
              this.$message.error('请添加数据');
              return
            }
            this.queryParams.createBy = this.user.name
            this.queryParams.companyId = this.user.id


            const res = await submitLeaseApply(this.queryParams)
            if(res.code == 200){
              this.$message({
                type:'success',
                message: '申请成功'
              })
              setTimeout(() => {
                this.$router.back()
              },1000)
            }
          }
      })


    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.back()
    },

    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      const deptTreeSelect = this.getDeptTree(row.roleId);
      getRole(row.roleId).then(response => {
        this.form = response.data;
        this.openDataScope = true;
        this.$nextTick(() => {
          deptTreeSelect.then(res => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
        this.title = "分配数据权限";
      });
    },
    /** 分配用户操作 */
    handleAuthUser: function(row) {
      const roleId = row.roleId;
      this.$router.push("/system/role-auth/user/" + roleId);
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.roleId != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            updateRole(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            addRole(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.leaseApplyDetails.splice(row.index,1)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/role/export', {
        ...this.queryParams
      }, `role_${new Date().getTime()}.xlsx`)
    },




    /////// 设备类型树  切换
    deviceTypeChange(val){
      let nodes = null;
      // nodes = this.$refs.deviceTypeCascader.getCheckedNodes().length > 0 ? this.$refs.deviceTypeCascader.getCheckedNodes() : this.$refs.deviceTypeCascader.panel.getNodeByValue(val)
      //
      nodes = this.$refs.deviceTypeCascader.getCheckedNodes()
      console.log(nodes)

      if(nodes[0].level != 4){
        return
      }

      this.leaseApplyDetails.push(
        this.handelTableItemData(nodes[0])
      )

      // this.$refs.cascader.$refs.panel.clearCheckedNodes()
      // // 设置为空可以让节点不高亮显示
      // this.$refs.cascader.$refs.panel.activePath = []
      this.deviceType = {}




    },
    //// 将数据处理成 表格中需要的数据
    handelTableItemData(node){
      const template = JSON.parse(JSON.stringify(this.leaseApplyDetailsItem))
      template.createBy = this.user.name
      template.companyId = this.user.id
      template.typeId = node.data.id
      template.unitCn = node.data.unitName
      template.typeCn = node.pathLabels[2]
      template.guigeCn = node.pathLabels[3]
      return template
    }
  }
};
</script>
