<template>
  <el-dialog
    title="派单"
    :visible.sync="addPatrolPlanDialog"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    custom-class="ele-dialog-form"
    width="90%"
    v-loading="editLoading"
  >
    <div class="dialog_body">
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addFormRules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="工单编号" prop="orderCode">
              <el-input
                v-model="addForm.orderCode"
                placeholder="自动带出"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联计划" prop="name">
              <el-input v-model="addForm.name" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执行部门" prop="executeGroupId">
              <deptSelect
                v-model="addForm.executeGroupId"
                @changeGroup="searchDeptNodeClick"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="执行人"
              prop="executeUserId"
              :rules="[{ required: true, message: '请选择执行人' }]"
            >
              <personSelect
                ref="executorRef"
                v-model="addForm.executeUserId"
                @selfChange="handleExecutorChange"
                :init="false"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 设备分类 -->
      <div class="equipment_box">
        <div class="left_aside">
          <div class="equipment_list_title">设备列表</div>
          <div class="equipment_tree">
            <el-tree
              :data="planDeviceList"
              :props="defaultProps"
              ref="equiListTree"
              highlight-current
              node-key="id"
              @node-click="handleNodeClick"
              show-checkbox
            ></el-tree>
          </div>
        </div>
        <div class="right_aside">
          <div class="equipment_info">
            <div class="item_info">
              <span class="item_label">设备编码</span>
              <span class="item_value">{{ equipmentInfo.equiCode }}</span>
            </div>
            <div class="item_info">
              <span class="item_label">设备名称</span>
              <span class="item_value">{{ equipmentInfo.equiName }}</span>
            </div>
            <div class="item_info">
              <span class="item_label">设备型号</span>
              <span class="item_value">{{ equipmentInfo.equiModel }}</span>
            </div>
            <div class="item_info">
              <span class="item_label">设备位置</span>
              <span class="item_value">{{ equipmentInfo.equiLocation }}</span>
            </div>
          </div>
          <!-- 操作事项 -->
          <div>
            <span type="text">操作事项</span>
            <el-table
              :data="
                planDeviceList[currentEquItemIndex] &&
                planDeviceList[currentEquItemIndex].workItems
              "
              border
            >
              <el-table-column label="序号" align="center" width="60">
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="事项" align="center" prop="name">
              </el-table-column>
              <el-table-column label="内容" align="center" prop="content">
              </el-table-column>
              <el-table-column label="标准" align="center" prop="norm">
              </el-table-column>
            </el-table>
          </div>

          <!-- 添加备品备件 -->
          <div v-if="type === '保养'">
            <span type="text">所需备件</span>
            <el-table
              :data="
                planDeviceList[currentEquItemIndex] &&
                planDeviceList[currentEquItemIndex].sparePart
              "
              height="300"
              :key="currentEquItemIndex"
              border
            >
              <el-table-column label="序号" align="center" width="60">
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="备件名称"
                align="center"
                prop="categoryName"
              >
              </el-table-column>
              <el-table-column label="规格型号" align="center" prop="model">
                <template slot-scope="{ row }">
                  <span>{{ row.specification }}/{{ row.model }}</span>
                </template>
              </el-table-column>
              <el-table-column label="所需数量" align="center" prop="needNum">
              </el-table-column>
              <el-table-column label="单位" align="center" prop="unit">
              </el-table-column>
              <el-table-column label="费用" align="center" prop="univalence">
                <template slot-scope="scope">
                  {{ scope.row.cost
                  }}{{ scope.row.parValue == 'wanyuan' ? '万元' : '元' }}
                </template>
              </el-table-column>
            </el-table>
            <div style="text-align: center"
              >备件总费用：
              {{ totalCost || '-' }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog_footer">
      <el-button type="primary" @click="submit(false)">提交</el-button>
      <el-button @click="handleClose">关闭</el-button>
      <el-link type="primary" @click="submit(true)">提交并继续指派</el-link>
    </div>
  </el-dialog>
</template>

<script>
  import personSelect from '@/components/CommomSelect/person-select.vue';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import { getCode } from '@/api/ruleManagement/matter';
  import {
    getById,
    getNotSendOrderList,
    sendOrder
  } from '@/api/maintenance/patrol_maintenance';
  export default {
    name: 'addPatrolPlanDialog',
    components: {
      // SelectTree,
      personSelect,
      deptSelect
    },
    props: {
      type: {
        type: String,
        default: '巡点检'
      }
    },
    data() {
      return {
        defaultProps: {
          label: 'showName'
        },
        addPatrolPlanDialog: false,
        equipmentInfo: {},
        clickedTreeNode: false,
        selectedMatter: [],
        selectedSpare: [],
        uerList: [],
        deptList: [],
        executorList: [],
        currentEquItemIndex: 0,
        formLabel: '',
        planRuleTypeObj: {
          1: 'PATROL',
          2: 'MAINTAIN',
          4: 'INVENTORY'
        },
        addForm: {
          executeGroupId: '',
          executeGroupName: '',
          executeUserId: '',
          executeUserName: '',
          orderCode: '',
          name: ''
        },
        // 计划规则设备列表
        planDeviceList: [
          // {
          //   equiTypeId: '', // 设备分类Id
          //   equiTypeName: '', // 设备分类名字
          //   equiCode: '', // 设备编码 equCode
          //   equiName: '', // 设备名称 name
          //   equiModel: '', // 设备型号 specifications
          //   equiLocation: '', // 设备位置
          //   equiLocationCode: '', // 设备位置code
          //   // 设备备品备件 - 巡点检不需要备品备件，保养需要
          //   sparePart: [],
          //   totalCost: 0
          // }
        ],
        addFormRules: {
          categoryLevelId: [
            { required: true, message: '请选择设备分类', trigger: 'change' }
          ],
          executeGroupId: [
            {
              required: true,
              message: '请选择选择执行部门',
              trigger: 'change'
            }
          ],
          executeUserId: [
            {
              required: true,
              message: '请选择选择执行人',
              trigger: 'change'
            }
          ]
        },
        ruleNameList: [],
        equipmentList: [],
        currentNode: null,
        rootId: null,
        editLoading: false
      };
    },
    async created() {},
    computed: {
      totalCost() {
        const cur = this.planDeviceList[this.currentEquItemIndex] || {};
        const sparePart = cur?.sparePart || [];

        return (
          (sparePart.reduce((sum, item) => {
            let chengs = 1;
            switch (item.parValue) {
              case 'wanyuan': {
                chengs = 10000;
                break;
              }
              case 'yuan': {
                chengs = 1;
                break;
              }
              default:
                break;
            }
            console.log(sum, item.cost);
            return sum + item.cost * chengs;
          }, 0) || 0) + '元'
        );
      }
    },
    methods: {
      open(row) {
        this.getInfo(row.id);
        this.addPatrolPlanDialog = true;
      },
      // 编辑详情
      async getInfo(planId) {
        this.editLoading = true;
        const res = await getById(planId).catch(() => {
          this.editLoading = false;
        });
        this.editLoading = false;
        if (res?.data) {
          this.addForm = res.data;
          this.getOrderCode();
          this._getEquipmentList(res.data.planId);
        }
      },

      // 获取计划配置单号
      async getOrderCode() {
        if (this.type.includes('巡点检')) {
          const data = await getCode('partrol_code');
          this.$set(this.addForm, 'orderCode', data);
        }
        if (this.type.includes('保养')) {
          const code = await getCode('maintenance_code');
          this.$set(this.addForm, 'orderCode', code);
        }
      },
      handleClose() {
        this.addPatrolPlanDialog = false;
        this.$refs.addFormRef.resetFields();
        this.currentEquItemIndex = 0;
        this.equipmentInfo = {};
        this.addForm = {};
      },
      // 设备列表树点击
      handleNodeClick(data, node) {
        const { equiLocation, equiLocationCode } = this.getEquiLocation(data);
        this.equipmentInfo = {
          equiCode: data.code,
          equiName: data.name,
          deviceId: data.id,
          equiModel: data.category.modelType,
          equiLocation: equiLocation,
          equiLocationCode: equiLocationCode
        };
        // 保存当前点击的设备列表某节点的index，在添加操作事项的时候，可以将事项list放到对应的节点对象中，以及切换节点的时候回显事项list
        this.currentEquItemIndex = this.planDeviceList.findIndex(
          (item) => item.code === data.code
        );
        this.clickedTreeNode = true;
        this.planDeviceList[this.currentEquItemIndex]['equiLocation'] =
          equiLocation;
        this.planDeviceList[this.currentEquItemIndex]['equiLocationCode'] =
          equiLocationCode;
      },
      // 封装 - 获取设备分类列表
      async _getEquipmentList(planId) {
        const data = await getNotSendOrderList(planId);
        if (!data?.length) {
          this.$message.error('所有设备已指派完!');
          this.handleClose();
          return;
        }
        this.planDeviceList = (data || []).map((item) => ({
          showName: item.substance?.name + '(' + item.substance?.code + ')',
          ...item,
          ...item.substance,
          id: item.id
        }));
        this.currentEquItemIndex = 0;
        const item = this.planDeviceList[0];
        const { equiLocation, equiLocationCode } = this.getEquiLocation(item);
        this.$nextTick(() => {
          this.$refs.equiListTree.setCurrentKey(item.id);
          this.equipmentInfo = {
            equiTypeId: this.addForm.categoryId,
            equiCode: item.code,
            equiName: item.name,
            equiModel: item.model,
            equiLocation: equiLocation,
            equiLocationCode: equiLocationCode
          };
          this.planDeviceList[0]['equiLocation'] = equiLocation;
          this.planDeviceList[0]['equiLocationCode'] = equiLocationCode;
        });
      },
      //选择部门(搜索)
      searchDeptNodeClick(id, info) {
        this.addForm.executeGroupName = info?.name;
        // 根据部门获取人员
        const params = { executeGroupId: id ? id : '' };
        this.$nextTick(() => {
          this.$refs.executorRef.getList(params);
        });
      },
      //执行人
      handleExecutorChange(id, info) {
        this.addForm.executeUserName = info?.name;
      },
      // 封装 - 获取设备位置名称和code方法
      getEquiLocation(data) {
        // 设备位置编码
        const equiLocationCode = data.position[0].pathIds;
        // 设备位置名称
        const equiLocation = data.position[0].pathName;
        return { equiLocation, equiLocationCode };
      },
      // 提交
      submit(isContinue = false) {
        this.$refs.addFormRef.validate(async (valid) => {
          if (valid) {
            try {
              const selectList = this.$refs.equiListTree.getCheckedKeys();
              if (!selectList.length) {
                this.$message.warning('请选择设备！');
                return;
              }

              // 将newData拼接成一个新数组赋值给后端接收字段
              const params = {
                executeGroupId: this.addForm.executeGroupId
                  ? this.addForm.executeGroupId
                  : '',
                executeGroupName: this.addForm.executeGroupName,
                executeUserId: this.addForm.executeUserId,
                executeUserName: this.addForm.executeUserName,
                orderCode: this.addForm.orderCode,
                planDeviceIds: selectList.join(','),
                planId: this.addForm.planId
              };

              await sendOrder(params);
              if (!isContinue) {
                this.handleClose();
              } else {
                this._getEquipmentList(this.addForm.planId);
              }
              this.$message.success('派单成功！');
              this.$emit('refreshList');
            } catch (error) {
              console.log(error);
            }
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  ::v-deep .el-form {
    .el-form-item__error {
      padding-top: 0;
    }
  }
  .equipment_box {
    display: flex;
    .left_aside {
      width: 300px;
      border: 1px solid #797979;
      margin-right: 5px;
      .equipment_list_title {
        height: 24px;
        line-height: 24px;
        text-align: center;
        background-color: #d7d7d7;
        color: #000;
        font-weight: 700;
      }
      .equipment_tree {
        height: 510px;
        overflow: auto;
      }
      ::v-deep .el-tree-node__expand-icon.el-icon-caret-right {
        padding: 0;
      }
      ::v-deep
        .el-tree--highlight-current
        .el-tree-node.is-current
        > .el-tree-node__content {
        background-color: #d7f1fd !important;
      }
    }
    .right_aside {
      flex: 1;
      border: 1px solid #797979;
      padding: 10px;
      .equipment_info {
        display: flex;
        flex-wrap: wrap;
        border: 1px solid #ddd;
        .item_info {
          width: 33%;
          height: 24px;
          line-height: 24px;
          display: flex;
          .item_label {
            width: 90px;
            text-align: center;
            background-color: #f2f2f2;
            font-weight: 700;
          }
          .item_value {
            border-bottom: 1px solid #f2f2f2;
            flex: 1;
            padding-left: 5px;
          }
          &:last-child {
            width: 100%;
            .item_value {
              border: 0;
            }
          }
        }
      }
    }
  }
  .dialog_footer {
    text-align: center;
    position: relative;
    .el-link {
      position: absolute;
      right: 0;
      top: 30%;
    }
  }
</style>
