<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="addPatrolConfigDialog"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    v-loading="addDialogLoading"
    width="80%"
  >
    <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="code">
              <el-input
                v-model="addForm.code"
                size="small"
                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"
                size="small"
                placeholder="请输入"
                :disabled="isBindPlan"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="自动派单" prop="autoOrder">
              <el-select
                v-model="addForm.autoOrder"
                size="small"
                style="width: 100%"
                :disabled="isBindPlan"
              >
                <el-option :value="1" label="是"></el-option>
                <el-option :value="0" label="否"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规则名称" prop="ruleId">
              <el-select
                v-model="addForm.ruleId"
                size="small"
                style="width: 100%"
                @change="handleRuleNameChange"
                :disabled="isBindPlan"
                filterable
              >
                <el-option
                  v-for="item in ruleNameList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                  @click.native="addForm.ruleName = item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划完成时长" prop="duration">
              <div style="display: flex">
                <el-input
                  v-model="addForm.duration"
                  size="small"
                  placeholder="请输入"
                  :disabled="isBindPlan"
                >
                  <template #suffix>分钟</template>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备分类" prop="categoryLevelId">
              <equipmentSelect
                v-model="addForm.categoryLevelId"
                @changeNode="chooseClassify"
                @setRootId="getRootId"
                :disabled="isBindPlan"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备类别" prop="categoryId">
              <el-select
                v-model="addForm.categoryId"
                size="small"
                style="width: 100%"
                :disabled="isBindPlan"
                filterable
              >
                <el-option
                  v-for="item in equipmentList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                  @click.native="handleEquipmentClassChange(item)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核人" prop="approvalUserId">
              <el-select
                v-model="addForm.approvalUserId"
                size="small"
                clearable
                style="width: 100%"
                :disabled="isBindPlan"
                filterable
              >
                <el-option
                  v-for="item in uerList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="addForm.autoOrder">
            <el-form-item :label="formLabel + '部门'" prop="groupId">
              <deptSelect
                v-model="addForm.groupId"
                @changeGroup="searchDeptNodeClick"
                :disabled="isBindPlan"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="addForm.autoOrder">
            <el-form-item :label="formLabel + '人员'" prop="executeIdList">
              <el-select
                v-model="addForm.executeIdList"
                size="small"
                style="width: 100%"
                :disabled="isBindPlan"
                multiple
                filterable
              >
                <el-option
                  v-for="item in executorList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="紧急程度" prop="urgent">
              <DictSelection
                dictName="紧急程度"
                clearable
                v-model="addForm.urgent"
                :disabled="isBindPlan"
              >
              </DictSelection>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="addForm.status"
                active-text="开"
                inactive-text="关"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                resize="none"
                v-model="addForm.remark"
                :rows="2"
                placeholder="请详细说明"
                size="small"
                :disabled="isBindPlan"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 设备分类 -->
        <div class="equipment_box">
          <div class="left_aside">
            <div class="equipment_list_title">设备列表</div>
            <div class="equipment_tree">
              <el-tree
                :data="planRuleEquiList"
                :props="defaultProps"
                ref="equiListTree"
                highlight-current
                node-key="id"
                @node-click="handleNodeClick"
                :disabled="isBindPlan"
                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>
              <div class="box_tips">操作事项</div>
              <el-table :data="matterRulesList" 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="dialogTitle.includes('保养')">
              <el-button
                type="text"
                @click="addSpareItems"
                :disabled="isBindPlan"
                >添加备品备件</el-button
              >
              <el-table
                :data="
                  planRuleEquiList[currentEquItemIndex] &&
                  planRuleEquiList[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">
                </el-table-column>
                <el-table-column label="所需数量" align="center" prop="needNum">
                  <template slot-scope="scope">
                    <el-input
                      v-model.number="scope.row.needNum"
                      size="small"
                      oninput="value=value.replace(/[^\d]/g,'')"
                      style="width: 100%"
                      placeholder="输入数量"
                      @input="changeNum"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单位" align="center" prop="unit">
                </el-table-column>
                <el-table-column label="费用" align="center">
                  <template slot-scope="scope">
                    {{
                      scope.row.needNum * scope.row.unitPrice
                        ? scope.row.needNum * scope.row.unitPrice
                        : '0'
                    }}{{ scope.row.parValue == 'wanyuan' ? '万元' : '元' }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="70">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      @click="handleDeleteSpareItem(scope.$index)"
                      :disabled="isBindPlan"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <div style="text-align: center"
                >备件总费用：
                {{
                  planRuleEquiList[currentEquItemIndex] &&
                  planRuleEquiList[currentEquItemIndex].totalCost
                    ? planRuleEquiList[currentEquItemIndex].totalCost
                    : '-'
                }}
                元
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <div slot="footer" class="dialog_footer">
      <el-button size="small" type="primary" @click="submit">提交</el-button>
      <el-button size="small" @click="handleClose">关闭</el-button>
    </div>
    <AddSpareDialog
      ref="addSpareDialogRef"
      :selectedSpare="selectedSpare"
      @submit="spareItemSelectSubmit"
    />
  </el-dialog>
</template>

<script>
  import RuleItemSelection from '@/components/ruleItemSelection';
  import AddSpareDialog from '@/components/addSpareDialog';
  import { deepClone } from '@/utils';
  import {
    getRule,
    getCategory,
    getAssetList,
    saveOrUpdate,
    getInfoById
  } from '@/api/ruleManagement/plan';
  import { getDetail, getCode } from '@/api/ruleManagement/matter';
  import { getUserPage } from '@/api/system/organization';
  import { getTreeByType } from '@/api/classifyManage';
  import equipmentSelect from '@/components/CommomSelect/equipment-select.vue';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  export default {
    name: 'addPatrolConfigDialog',
    components: {
      RuleItemSelection,
      AddSpareDialog,
      equipmentSelect,
      deptSelect
    },
    props: {
      dialogTitle: {
        type: String,
        default: () => {
          return '新增巡点检计划配置';
        }
      }
    },
    data() {
      return {
        defaultProps: {
          label: 'showName'
        },
        addPatrolConfigDialog: false,
        matterRulesList: [], // 选择规则名称的时候，获取的事项
        equipmentInfo: {},
        clickedTreeNode: false,
        selectedMatter: [],
        selectedSpare: [],
        uerList: [],
        // deptList: [],
        executorList: [],
        currentEquItemIndex: 0,
        formLabel: '',
        treeData: [],
        addForm: {
          code: '', // 计划配置单号
          name: '', // 计划配置名称
          autoOrder: 1, // 自动派单
          ruleId: '', // 规则id
          ruleName: '', // 规则名称
          duration: null, // 计划完成时长
          categoryId: '', // 设备类别id
          approvalUserId: '', // 审核人id
          groupId: '', // 巡点检部门code
          executeIdList: [], // 巡点检人员id
          executorPhone: '',
          status: 1, // 状态
          remark: '', // 备注
          urgent: ''
        },
        // 计划规则设备列表
        planRuleEquiList: [
          {
            equiCode: '', // 设备编码 equCode
            equiName: '', // 设备名称 name
            equiModel: '', // 设备型号 specifications
            equiLocation: '', // 设备位置
            // 设备备品备件 - 巡点检不需要备品备件，保养需要
            sparePart: [],
            totalCost: 0
          }
        ],
        addFormRules: {
          name: [
            { required: true, message: '请输入计划配置名称', trigger: 'blur' }
          ],
          autoOrder: [
            { required: true, message: '请选择是否自动派单', trigger: 'change' }
          ],
          ruleId: [
            { required: true, message: '请选择规则名称', trigger: 'change' }
          ],
          duration: [
            { required: true, message: '请输入计划完成时长', trigger: 'blur' }
          ],
          categoryLevelId: [
            { required: true, message: '请选择设备分类', trigger: 'change' }
          ],
          categoryId: [
            { required: true, message: '请选择设备类别', trigger: 'change' }
          ],
          groupId: [
            { required: true, message: '请选择巡点检部门', trigger: 'change' }
          ],
          executeIdList: [
            { required: true, message: '请选择巡点检人员', trigger: 'change' }
          ],
          urgent: [
            { required: true, message: '请选择紧急程度', trigger: 'change' }
          ]
        },
        ruleNameList: [],
        addDialogLoading: false,
        equipmentList: [],
        rootId: null,
        isBindPlan: false
      };
    },
    computed: {},
    watch: {
      addPatrolConfigDialog(val) {
        if (val) {
          this.formLabel = this.dialogTitle.includes('巡点检')
            ? '巡点检'
            : this.dialogTitle.includes('保养')
            ? '保养'
            : '盘点';
          // 获取审核人列表数据
          this.getUserList();
          // 获取部门
          // this.getDeptList()
          // 获取规则名称
          this._getRuleNameList();
        }
      }
    },
    created() {},
    methods: {
      async init(row, tips) {
        if (row) {
          this.getInfo(row.id);
        } else {
          //  获取计划配置单号
          this.getOrderCode(tips);
          this.isBindPlan = false;
          this.planRuleEquiList = [];
          this.matterRulesList = [];
        }
      },

      async getInfo(id) {
        const res = await getInfoById(id);
        this.addForm = res;
        this.isBindPlan = res.isBindPlan;
        this.categoryEquipment(res.categoryLevelId);
        const params = { groupId: res.groupId };
        this.getUserList(params);
        this._getMatterRulesDetails(res.ruleId);
        this.$set(this.addForm, 'code', res.code);
        this.$set(this.addForm, 'urgent', JSON.stringify(res.urgent));
        this.$set(this.addForm, 'executeIdList', res.executeId.split(','));
        this.$set(this.addForm, 'imageUrl', {});
        this._getEquipmentList(res.categoryId, this.isBindPlan);
        let keys = [];
        res.deviceInfo.map((item) => {
          keys.push(item.substanceId);
        });
        this.$nextTick(() => {
          this.$refs.equiListTree.setCheckedKeys(keys);
        });
        this.clickedTreeNode = true;
      },

      handleClose() {
        this.clickedTreeNode = false;
        this.addPatrolConfigDialog = false;
        this.$refs.addFormRef.resetFields();
        if (this.$refs.equiListTree) {
          this.$refs.equiListTree.setCheckedKeys([]);
        }
        this.currentEquItemIndex = 0;
        this.equipmentInfo = {};
        this.addForm = {
          code: '', // 计划配置单号
          name: '', // 计划配置名称
          autoOrder: 1, // 自动派单
          ruleId: '', // 规则id
          duration: null, // 计划完成时长
          categoryId: '', // 设备类别
          approvalUserId: '', // 审核人id
          groupId: '', // 巡点检部门code
          executeIdList: [], // 巡点检人员id
          executorPhone: '',
          status: 1, // 状态
          remark: '', // 备注
          urgent: ''
        };
        this.equipmentList = [];
      },
      // 设备分类选择
      async handleEquipmentClassChange(item) {
        this.clickedTreeNode = true;
        this.equipmentInfo = {};
        this._getEquipmentList(item.id, this.isBindPlan);
      },
      // 封装 - 获取设备分类列表
      async _getEquipmentList(val, bind) {
        const params = {
          pageNum: 1,
          size: -1,
          categoryId: val,
          rootCategoryLevelId: this.rootId
        };
        const res = await getAssetList(params);
        this.planRuleEquiList = res.list;
        if (!res.list.length) return;
        this.planRuleEquiList.map((item) => {
          item.showName = item.name + '(' + item.code + ')';
          item.disabled = bind;
        });
        this.currentEquItemIndex = 0;
        const item = this.planRuleEquiList[0];
        this.$nextTick(() => {
          this.$refs.equiListTree.setCurrentKey(item.id);
          this.equipmentInfo = {
            equiCode: item.code,
            equiName: item.name,
            equiModel: item.category.modelType,
            equiLocation: item.position[0].pathName
          };
          // 对比详情返回的数据和设备分类下面所有的设备列表，将sparePart同步过去
          if (this.addForm.deviceInfo) {
            for (let i = 0; i < this.planRuleEquiList.length; i++) {
              for (let j = 0; j < this.addForm.deviceInfo.length; j++) {
                if (
                  this.planRuleEquiList[i].code ===
                  this.addForm.deviceInfo[j].substance.code
                ) {
                  this.$set(
                    this.planRuleEquiList[i],
                    'sparePart',
                    this.addForm.deviceInfo[j].sparePart
                  );
                  this.$set(
                    this.planRuleEquiList[i],
                    'totalCost',
                    this.addForm.deviceInfo[j].totalCost
                  );
                }
              }
            }
          }
        });
      },

      // 获取审核人列表、巡点检人员
      async getUserList(params) {
        try {
          let data = { pageNum: 1, size: -1 };
          // 如果传了参数就是获取巡点检人员数据
          if (params) {
            data = Object.assign(data, params);
          }
          const res = await getUserPage(data);
          if (params) {
            this.executorList = res.list;
          } else {
            this.uerList = res.list;
          }
        } catch (error) {}
      },

      //选择部门(搜索)
      searchDeptNodeClick(info) {
        if (info) {
          // 根据部门获取人员
          const params = { groupId: info };
          this.getUserList(params);
        } else {
          this.addForm.groupId = null;
        }
      },

      // 分类树的选择
      chooseClassify(val) {
        this.categoryEquipment(val);
      },

      getRootId(val) {
        this.rootId = val;
      },

      // 获取设备分类数据
      async categoryEquipment(id) {
        const params = { categoryLevelId: id, pageNum: 1, size: -1 };
        const data = await getCategory(params);
        // this.addForm.categoryId = '';
        this.equipmentList = data.list;
      },

      // 获取计划配置单号
      async getOrderCode(tips) {
        if (tips.includes('巡点检')) {
          const data = await getCode('patrolconfig_code');
          this.$set(this.addForm, 'code', data);
        }
        if (tips.includes('保养')) {
          const code = await getCode('maintainconfig_code');
          this.$set(this.addForm, 'code', code);
        }
      },

      // 设备列表树点击
      handleNodeClick(data, node) {
        this.equipmentInfo = {
          equiCode: data.code,
          equiName: data.name,
          equiId: data.id,
          equiModel: data.category.modelType,
          equiLocation: data.position[0].pathName
        };
        // 保存当前点击的设备列表某节点的index，在添加操作事项的时候，可以将事项list放到对应的节点对象中，以及切换节点的时候回显事项list
        this.currentEquItemIndex = this.planRuleEquiList.findIndex(
          (item) => item.code === data.code
        );
        this.clickedTreeNode = true;
      },
      // 获取规则名列表
      async _getRuleNameList() {
        if (
          this.dialogTitle === '新增保养计划配置' ||
          this.dialogTitle === '编辑保养计划配置'
        ) {
          const res = await getRule({
            status: 1,
            type: 2,
            pageNum: 1,
            size: -1
          });
          if (res.list) {
            this.ruleNameList = res.list || [];
          }
        }
        if (
          this.dialogTitle === '新增巡点检计划配置' ||
          this.dialogTitle === '编辑巡点检计划配置'
        ) {
          const res = await getRule({
            status: 1,
            type: 1,
            pageNum: 1,
            size: -1
          });
          if (res.list) {
            this.ruleNameList = res.list || [];
          }
        }
      },
      // 规则名称下拉触发
      handleRuleNameChange(val) {
        this._getMatterRulesDetails(val);
      },
      // 封装 - 获取规则下面的详情数据及事项
      async _getMatterRulesDetails(val) {
        const res = await getDetail(val);
        this.matterRulesList = res.ruleItems;
      },

      // 添加备品备件
      addSpareItems() {
        if (!this.clickedTreeNode) {
          return this.$message.warning('请选择设备分类！');
        }
        this.$refs.addSpareDialogRef.open();
        if (this.planRuleEquiList[this.currentEquItemIndex]['sparePart']) {
          this.selectedSpare =
            this.planRuleEquiList[this.currentEquItemIndex]['sparePart'];
        } else {
          this.selectedSpare = [];
        }
        // console.log('this.selectedSpare',this.selectedSpare)
      },

      // 从备品备件弹窗将数据丢到备品备件配置
      spareItemSelectSubmit(list) {
        this.planRuleEquiList[this.currentEquItemIndex]['sparePart'] = list.map(
          (item) => {
            return {
              categoryName: item.name,
              model: item.modelType,
              needNum: item.num,
              parValue: item.univalenceUnit,
              unitPrice: item.univalence,
              unit: item.measuringUnit,
              code: item.code,
              id: item.id
            };
          }
        );
        this.$forceUpdate();
      },

      // 删除备品备件
      handleDeleteSpareItem(index) {
        this.planRuleEquiList[this.currentEquItemIndex]['sparePart'].splice(
          index,
          1
        );
        this.changeNum();
      },

      // 改变input数据重新计算总费用
      changeNum() {
        let applayList =
          this.planRuleEquiList[this.currentEquItemIndex].sparePart;
        let total = 0;
        applayList.map((item) => {
          if (item.needNum && item.needNum != '') {
            switch (item.parValue) {
              case 'wanyuan': {
                item.chengs = 10000;
                break;
              }
              case 'yuan': {
                item.chengs = 1;
                break;
              }
              default:
                break;
            }
            item.cost = item.needNum * item.unitPrice * item.chengs;
            total = total + item.needNum * item.unitPrice * item.chengs;
          }
        });
        this.$set(
          this.planRuleEquiList[this.currentEquItemIndex],
          'totalCost',
          total
        );
      },

      // 提交
      submit() {
        this.$refs.addFormRef.validate(async (valid) => {
          if (valid) {
            try {
              const selectList = this.$refs.equiListTree.getCheckedNodes();
              this.addForm.deviceInfo = selectList.map((item) => {
                return {
                  substanceId: item.id,
                  sparePart: item.sparePart ? item.sparePart : [],
                  totalCost: item.totalCost
                };
              });
              this.addForm.executeId = this.addForm.executeIdList.join(',');
              this.addForm.ruleType = this.dialogTitle.includes('巡点检')
                ? 1
                : this.dialogTitle.includes('保养')
                ? 2
                : 3;
              this.addForm.isBindPlan = this.isBindPlan;
              const res = await saveOrUpdate(this.addForm);
              if (res) {
                const type = this.dialogTitle.includes('新增')
                  ? '新增'
                  : '编辑';
                this.handleClose();
                this.$message.success(type + '成功！');
                this.$emit('done');
              }
            } catch (error) {}
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  :deep(.el-form) {
    .el-form-item {
      margin-bottom: 14px;
    }
    .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: 34px;
        line-height: 34px;
        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: 34px;
          line-height: 34px;
          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;
  }
  .box_tips {
    color: #1890ff;
    margin: 10px 0;
  }
</style>
