<template>
  <!-- 新增工机具 -->
  <div>
    <el-form
      :model="maForm"
      ref="maForm"
      size="small"
      :rules="rules"
      :inline="true"
      label-width="120px"
    >
      <!-- <el-form-item label="租赁单位" prop="leaseUnitId">
        <el-select
          v-model="maForm.leaseUnitId"
          placeholder="请选择租赁单位"
          clearable
          filterable
          style="width: 240px"
          @change="uniteChange"
        >
          <el-option
            v-for="item in uniteList"
            :key="item.unitId"
            :label="item.unitName"
            :value="item.unitId"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="租赁单位" prop="unitId">
        <el-cascader
          v-model="unitId"
          :show-all-levels="false"
          :options="uniteList"
          :props="selectTreeProps"
          filterable
          clearable
          collapse-tags
          @change="uniteChange"
          :disabled="isEdit"
          placeholder="请选择租赁单位"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="租赁工程" prop="projectId">
        <el-cascader
          v-model="projectId"
          :show-all-levels="false"
          :options="projectList"
          :props="selectTreeProps"
          filterable
          clearable
          collapse-tags
          @change="projectChange"
          :disabled="isEdit"
          placeholder="请选择租赁工程"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="领料人" prop="leasePerson">
        <el-input
          v-model="maForm.leasePerson"
          placeholder="请输入领料人"
          clearable
          maxlength="50"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input
          v-model="maForm.phone"
          placeholder="请输入联系电话"
          clearable
          maxlength="50"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="类型规格" prop="deviceType">
        <el-cascader
          :key="propsKey"
          v-model="deviceType"
          :show-all-levels="false"
          :options="equipmentTypeList"
          :props="deviceTypeTreeProps"
          filterable
          collapse-tags
          style="width: 240px"
          placeholder="请选择规格型号"
          ref="deviceTypeCascader"
          popper-class="popper-select"
          @change="deviceTypeChange"
        ></el-cascader>
      </el-form-item>
    </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="handleSave"
          >保存</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-if="isEdit">导出</el-button>
            </el-col> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="equipmentList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column align="center" label="序号" type="index" width="55" />
      <el-table-column
        align="center"
        label="类型名称"
        prop="maTypeName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        align="center"
        label="规格型号"
        prop="typeName"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="计量单位" prop="unitName" />
      <el-table-column align="center" label="当前库存" prop="storageNum" />
      <el-table-column label="预领数量" prop="preNum" align="center">
        <template v-slot="scope">
          <el-input-number
            v-model.number="scope.row.preNum"
            controls-position="right"
            style="width: 100%"
            :min="1" :max="scope.row.storageNum"
          ></el-input-number>
        </template>
      </el-table-column>

      <!-- <el-table-column align="center" label="出库数量" prop="alNum" /> -->
      <el-table-column
        label="备注"
        prop="remark"
        align="center"
        label-width="500px"
      >
        <template v-slot="scope">
          <el-input
            v-model="scope.row.remark"
            controls-position="right"
            style="width: 100%"
          ></el-input>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            style="color: red"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {
  getPurchaseCheckInfo,
  equipmentTypeTree,
} from "@/api/purchase/goodsArrived";
import {
  getListProject,
  getListUnite,
  addApplyInfo,
  updateApplyInfo,
  getApplyInfo,
  getAgreement,
} from "@/api/lease/apply";
import { getToken } from "@/utils/auth";
import {
  uploadPurchaseFile,
  getPurchaseFileList,
} from "@/api/purchase/goodsAccept";

// import Treeselect from '@riophae/vue-treeselect'
// import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// import HoldingpoleDialog from '@/components/HoldingpoleDialog/index.vue'

export default {
  name: "AddTools",
  dicts: ["purchase_task_status"],
  // components: { Treeselect, HoldingpoleDialog },
  props: {
    isEdit: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    editTaskId: {
      type: [String, Number],
      default: () => {
        return "";
      },
    },
    editId: {
      type: [String, Number],
      default: () => {
        return "";
      },
    },
  },
  data() {
    return {
      taskId: "",
      // isEdit: false,
      // 遮罩层
      loading: false,
      loadingTwo: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      selectTreeProps: {
        children: "children",
        label: "name",
        // multiple: false,
        value: "id",
        // multiple: true,
      },
      //租赁单位
      uniteList: [],
      //租赁工程
      projectList: [],
      //机具类型
      equipmentTypeList: [],
      // 角色表格数据
      equipmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      rowData: {},
      unitId: null,
      projectId: null,
      // 查询参数
      queryParams: {
        equipmentId: undefined,
        productionTime: "",
      },
      maForm: {
        unitId: undefined,
        projectId: undefined,
        arrivalTime: "",
        purchaser: "",
        remark: "",
        purchaseNumber: "",
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        unitId: [
          {
            required: true,
            message: "请选择租赁单位",
            trigger: "blur",
          },
        ],
        projectId: [
          {
            required: true,
            message: "请选择租赁工程",
            trigger: "blur",
          },
        ],
        leasePerson: [
          {
            required: true,
            message: "请输入领料人",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        // purchaser: [
        //   { required: true, message: "采购员不能为空", trigger: "blur" }
        // ]
      },
      deviceTypeTreeProps: {
        children: "children",
        label: "typeName",
        // multiple: false,
        value: "typeId",
        multiple: true,
      },
      deviceType: [],
      propsKey: 1000,
      projectTemp: undefined,
      unitTemp: undefined,
      agreementId: undefined,
      // taxRate:0,
    };
  },
  computed: {
    pickerOptions() {
      return {
        disabledDate(time) {
          const currentDate = new Date();
          currentDate.setHours(0, 0, 0, 0);
          return time.getTime() < currentDate.getTime();
        },
      };
    },
  },
  watch: {},
  mounted() {
    this.projectInfoList();//单位工程下拉选
    this.equipmentType();//机具类型下拉选
    if (this.isEdit) {
      console.log("isEdit", this.isEdit);
      this.taskId = this.editTaskId;
      this.id = this.editId;
      this.getTaskInfo();
      this.equipmentType();
    }
    // this.projectInfoList();
    // this.equipmentType();
  },
  methods: {
    uniteChange(val) {
      // this.projectList = [];
      if (val && val.length > 0) {
        this.maForm.unitId = this.unitId[this.unitId.length - 1];
      } else if (val && val.length == 0) {
        this.maForm.unitId = "";
      }
      getListProject({ unitId: this.maForm.unitId }).then((response) => {
        this.projectList = response.data;
      });
      // this.unitTemp = this.unitid;
    },
    projectChange(val) {
      if (val && val.length > 0) {
        this.maForm.projectId = this.projectId[this.projectId.length - 1];
      } else if (val && val.length == 0) {
        this.maForm.projectId = "";
      }
      getListUnite({ projectId: this.maForm.projectId }).then((response) => {
        this.uniteList = response.data;
      });
      // this.projectTemp = this.projectId;
    },
    /** 租赁单位和工程-下拉选 */
    projectInfoList() {
      if (!this.isEdit) {
        getListUnite({ projectId: null }).then((response) => {
          this.uniteList = response.data;
        });
        getListProject({ unitId: null }).then((response) => {
          this.projectList = response.data;
        });
      } else {
        getListUnite({ projectId: null }).then((response) => {
          this.uniteList = response.data;
        });
        getListProject({ unitId: this.maForm.unitId }).then((response) => {
          this.projectList = response.data;
        });
      }
      // getListProject({ id: null }).then((response) => {
      //   this.projectList = response.data;
      // });
    },
    // filterTree(nodes) {
    //   return nodes.map((node) => {
    //     if (node.children) {
    //       node.children = this.filterTree(node.children);
    //     }
    //     return node;
    //   });
    // },
    //选择物资厂家
    // changeSupplier(supplierId) {
    //     this.equipmentList.forEach((item) => {
    //         this.$set(item, 'supplierId', supplierId)
    //     })
    // },
    /** 机具类型 */
    equipmentType() {
      equipmentTypeTree().then((response) => {
        this.equipmentTypeList = response.data;
        this.equipmentTypeList.forEach((item, index) => {
          if (item.children && item.children.length > 0) {
            item.children.forEach((item2, index2) => {
              if (item2.children && item2.children.length > 0) {
                item2.children.forEach((item3) => {
                  if (item3.children && item3.children.length > 0) {
                    item3.children.forEach((item4) => {
                      item4.maTypeName = item3.typeName;
                      item4.specificationType = item4.typeName;
                      // this.$set(item4, "purchaseTaxPrice", 0);
                      // this.$set(item4, "purchasePrice", 0);
                    });
                  }
                });
              }
            });
          }
        });
        //反显
        let selectList = [];
        this.equipmentList.forEach((e) => {
          selectList.push(
            this.getParentsById(this.equipmentTypeList, e.typeId)
          );
        });
        this.deviceType = selectList;
      });
    },
    //添加机具类型
    deviceTypeChange(val) {
      const deviceTypeList = this.$refs.deviceTypeCascader.getCheckedNodes();
      let tempList = [];
      if (val.length > 0) {
        const items = val.map((e) => {
          return e[3];
        });
        for (let i of items) {
          for (let z of deviceTypeList) {
            if (z.data.typeId === i) {
              const obj = JSON.parse(JSON.stringify(z.data));
              obj.preNum = 1;
              if(obj.storageNum<=0){ 
                let index = this.deviceType.length; 
                if(index==1){
                  this.$nextTick(() => {
                    this.deviceType=[]; // 可选，如果你想要重置选中状态
                  });
                }else{
                  this.deviceType=this.deviceType.splice(0,1)
                }
                this.$modal.msgError("所选物资规格类型库存量为空！");
              }else{
                tempList.push(obj);
              }
              break;
            }
          }
        }
        const newDataListNew = [...this.equipmentList, ...tempList];
        const map = new Map();
        for (let item of newDataListNew) {
          if (!map.has(item.typeId)) {
            map.set(item.typeId, item);
          }
        }
        const newArray = [...map.values()];
        let newArray_array = [];
        items.forEach((e) => {
          newArray.forEach((j) => {
            if (e == j.typeId) {
              newArray_array.push(j);
            }
          });
        });
        this.equipmentList = newArray_array;
      } else {
        this.equipmentList = [];
      }
    },
    //获取任务详情--- 编辑回显数据
    async getTaskInfo() {
      // this.loading = true;
      await getApplyInfo(this.id).then((response) => {
        this.maForm = response.data.leaseApplyInfo;
        this.maForm.unitId = response.data.leaseApplyInfo.leaseUnitId;
        this.maForm.projectId = response.data.leaseApplyInfo.leaseProjectId;
        this.unitId = this.treeParentsById(this.uniteList, this.maForm.unitId);
        this.projectId = this.treeParentsById(
          this.projectList,
          this.maForm.projectId
        );
        this.equipmentList = response.data.leaseApplyDetailsList;
        // this.loading = false;
      });
      // await this.projectInfoList();
    },
    checkNum(row) {
        // let maxNum = row.storageNum
        // if (row.preNum <= 1) {
        //     row.preNum = 1
        // } else if (row.preNum > maxNum) {
        //     row.preNum = maxNum-1
        // }
    },
    //单位，工程树结构数据获取父
    treeParentsById(list, id) {
      for (let i in list) {
        if (list[i].id == id) {
          //查询到就返回该数组对象的value
          return [list[i].id];
        }
        if (list[i].children) {
          let node = this.treeParentsById(list[i].children, id);
          if (node !== undefined) {
            //查询到把父节把父节点加到数组前面
            node.unshift(list[i].id);
            return node;
          }
        }
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.roleId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 保存按钮操作 */
    handleSave() {
      // console.log(this.equipmentList)
      console.log("maForm", this.maForm);
      if (this.equipmentList.length > 0) {
        this.$refs["maForm"].validate(async (valid) => {
          if (valid) {
            console.log("projectId", this.projectTemp);
            await getAgreement({
              unitId: this.maForm.unitId,
              projectId: this.maForm.projectId,
            }).then((response) => {
              this.agreementId = response.data.agreementId;
              this.maForm.agreementId = this.agreementId;
            });
            this.maForm.taskId = this.taskId;
            // this.maForm.checkDetailsList = this.equipmentList
            await this.$modal
              .confirm("是否确认保存当前页面")
              .then(function () {})
              .then(() => {
                if (this.isEdit) {
                  this.maForm.leaseUnitId = this.maForm.unitId;
                  this.maForm.leaseProjectId = this.maForm.projectId;
                  console.log("编辑");
                  this.loading = true;
                  updateApplyInfo({
                    leaseApplyDetailsList: this.equipmentList,
                    leaseApplyInfo: this.maForm,
                  }).then((response) => {
                    if (response.code == 200) {
                      this.$modal.msgSuccess("编辑成功");
                      // this.$tab.closeOpenPage({
                      //     path: '/store/newBuy/newDevicesList',
                      // })

                      this.$emit("addToolsSuccess");
                    }
                    this.loading = false;
                  });
                } else if (!this.isEdit) {
                  console.log("新增");
                  // console.log(this.equipmentList)
                  this.loading = true;
                  addApplyInfo({
                    leaseApplyDetailsList: this.equipmentList,
                    leaseApplyInfo: this.maForm,
                  }).then((response) => {
                    if (response.code == 200) {
                      this.$modal.msgSuccess("新增成功");
                      // this.$tab.closeOpenPage({
                      //     path: '/store/newBuy/newDevicesList',
                      // })

                      this.$emit("addToolsSuccess");
                    }
                    this.loading = false;
                  });
                }
              })
              .catch(() => {});
          }
        });
      } else {
        this.$modal.msgError("请先添加类型规格");
      }
    },
    //文件管理
    openFileDialog(row) {
      this.rowData = row;
      this.fileDataList = [
        { dictLabel: "合格证", fileType: "0", name: "", url: "" },
        { dictLabel: "型式试验报告", fileType: "1", name: "", url: "" },
        { dictLabel: "出厂检测报告", fileType: "2", name: "", url: "" },
        { dictLabel: "第三方监测报告", fileType: "3", name: "", url: "" },
        { dictLabel: "其他报告", fileType: "4", name: "", url: "" },
      ];
      if (this.taskId == "") {
        // console.log(this.rowData)
        // console.log(this.rowData.bmFileInfos)
        if (this.rowData.bmFileInfos.length > 0) {
          this.rowData.bmFileInfos.forEach((item) => {
            let index = this.fileDataList.findIndex(
              (v) => v.fileType == item.fileType
            );
            this.fileDataList[index].name = item.name;
            this.fileDataList[index].url = item.url;
          });
        }
      } else {
        this.getFileData();
      }
      this.open = true;
    },
    getFileData() {
      let param = {
        modelId: this.rowData.typeId,
        taskType: 0,
        taskId: this.rowData.taskId,
      };
      getPurchaseFileList(param)
        .then((response) => {
          if (response.rows.length > 0) {
            response.rows.forEach((item) => {
              let index = this.fileDataList.findIndex(
                (v) => v.fileType == item.fileType
              );
              this.fileDataList[index].name = item.name;
              this.fileDataList[index].url = item.url;
            });
          }
        })
        .catch(() => {});
    },
    beforeFileUpload(row) {
      this.rowData.fileType = row.fileType;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code == 200) {
        if (this.taskId == "") {
          //新增逻辑
          // console.log(response)
          // console.log(this.rowData)
          // console.log(this.rowData.bmFileInfos)
          let obj = {
            taskId: this.taskId,
            taskType: "0",
            name: response.data.name,
            url: response.data.url,
            modelId: this.rowData.typeId,
            fileType: this.rowData.fileType,
            //   "dictLabel": this.rowData.dictLabel,
          };
          //根据文件上传返回更新文件管理弹窗内容
          let index = this.fileDataList.findIndex(
            (v) => v.fileType == this.rowData.fileType
          );
          this.fileDataList[index].name = response.data.name;
          this.fileDataList[index].url = response.data.url;
          //判断当前上传的文件是否已上传过-再往机具类型数据中插入
          if (this.rowData.bmFileInfos.length > 0) {
            let index2 = this.rowData.bmFileInfos.findIndex(
              (v) => v.fileType == this.rowData.fileType
            );
            if (index2 > -1) {
              //相同类型文件重复上传-替换
              this.rowData.bmFileInfos.splice(index2, 0, obj);
            } else {
              //不存在相同类型文件-添加
              this.rowData.bmFileInfos.push(obj);
            }
          } else {
            this.rowData.bmFileInfos.push(obj);
          }
        } else {
          //编辑逻辑
          let param = {
            taskId: this.taskId,
            taskType: "0",
            name: response.data.name,
            url: response.data.url,
            modelId: this.rowData.typeId,
            fileType: this.rowData.fileType,
            //   "dictLabel": this.rowData.dictLabel,
          };
          uploadPurchaseFile(param)
            .then((response) => {
              this.$modal.msgSuccess("上传成功");
              this.getFileData();
            })
            .catch(() => {
              this.$modal.msgError("上传失败");
            });
        }
      }
    },
    //图片查看
    picturePreview(file) {
      this.dialogImageUrl = file.url;
      const parts = file.name.split(".");
      const extension = parts.pop();
      if (extension === "doc" || extension === "docx" || extension === "pdf") {
        const windowName = file.name;
        window.open(file.url, windowName);
      } else {
        this.dialogVisible = true;
      }
    },
    //树结构数据获取父
    getParentsById(list, id) {
      for (let i in list) {
        if (list[i].typeId == id) {
          //查询到就返回该数组对象的value
          return [list[i].typeId];
        }
        if (list[i].children) {
          let node = this.getParentsById(list[i].children, id);
          if (node !== undefined) {
            //查询到把父节把父节点加到数组前面
            node.unshift(list[i].typeId);
            return node;
          }
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row)
      this.$modal
        .confirm("是否确认删除所选择的数据项？")
        .then(() => {
          this.deviceType.forEach((e, index) => {
            console.log("e", e);
            if (e[3] === row.typeId) {
              this.deviceType.splice(index, 1);
              this.propsKey++;
            }
          });
          console.log(this.equipmentList)
          this.equipmentList.forEach((item, index) => {
            if (item.typeId == row.typeId) {
              this.equipmentList.splice(index, 1);
            }
          });
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/material/purchase_check_info/exportDetails",
        { taskId: this.taskId },
        `新购到货详情_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss">
.popper-select {
  .el-cascader-panel .el-scrollbar .el-checkbox {
    display: none;
  }

  .el-cascader-panel .el-scrollbar:nth-child(4) .el-checkbox {
    display: block !important;
  }
}
</style>
