<template>
  <ele-modal
    :visible.sync="visible"
    :title="title"
    width="60vw"
    append-to-body
    @close="cancel"
  >
    <div class="switch" v-if="type == 'detail'">
      <div class="switch_left">
        <ul>
          <li
            v-for="item in tabOptions"
            :key="item.key"
            :class="{ active: activeComp == item.key }"
            @click="activeComp = item.key"
          >
            {{ item.name }}
          </li>
        </ul>
      </div>
    </div>

    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="create-form"
      v-if="activeComp === 'main'"
    >
      <headerTitle title="基本信息" style="margin-top: 15px"></headerTitle>
      <el-button
        size="small"
        type="primary"
        class="ele-btn-icon"
        style="margin-left: 15px; margin-bottom: 15px"
        @click="changeTemplateList"
        v-if="type == 'add'"
      >
        选择模板
      </el-button>
      <el-row :gutter="15">
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="处置方式:" prop="disposalType">
            <DictSelection
              dictName="设备处置方式"
              v-model="form.disposalType"
              :disabled="type == 'detail'"
              @change="disposalTypeChange"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="编码:" prop="code">
            <el-input v-model="form.code" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="名称:" prop="name">
            <el-input v-model="form.name" :disabled="type == 'detail'" />
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="管理类别:" prop="managementCategory">
            <DictSelection
              dictName="管理类别"
              v-model="form.managementCategory"
              :disabled="type == 'detail'"
            ></DictSelection>
          </el-form-item>
        </el-col>
     
      </el-row>

      <headerTitle title="处置对象" style="margin-top: 15px"></headerTitle>
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="deviceList"
        row-key="id"
        height="30vh"
        :needPage="false"
      >
        <template v-slot:toolbar>
          <div
            class="add-product"
            @click="addEquipment"
            v-if="type != 'detail'"
          >
            <i class="el-icon-circle-plus-outline"></i>
          </div>
        </template>
        <template v-slot:modelType="{ row }">
          <span>{{ row.category.modelType }}</span>
        </template>
        <template v-slot:specification="{ row }">
          <span>{{ row.category.specification }}</span>
        </template>
        <template v-slot:originalValue="{ row }">
          <el-input v-model="row.originalValue" :disabled="type == 'detail'" />
        </template>
        <template v-slot:netWorth="{ row }">
          <el-input v-model="row.netWorth" :disabled="type == 'detail'" />
        </template>
        <template v-slot:scrapValue="{ row }">
          <el-input v-model="row.scrapValue" :disabled="type == 'detail'" />
        </template>
        <template v-slot:action="{ row }">
          <el-popconfirm
            v-if="type != 'detail'"
            class="ele-action"
            title="确定要删除吗？"
            @confirm="del(row.id)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
      <headerTitle title="处置业务" style="margin-top: 15px">
        <template v-slot:action>
          <!-- <el-button
          size="small"
          type="primary"
          class="ele-btn-icon"
          style="margin-left: 15px"
          @click="infoDisposalVisible = true"
        >
          新增处置业务
        </el-button> -->
        </template>
      </headerTitle>
      <el-form label-width="150px" class="create-form">
        <el-button
          size="small"
          type="primary"
          class="ele-btn-icon"
          style="margin-left: 15px; margin-bottom: 15px"
          @click="infoDisposalVisible = true"
          v-if="type != 'detail'"
        >
          新增处置业务
        </el-button>
        <el-row :gutter="15">
          <el-col
            v-bind="styleResponsive ? { lg: 24, md: 24 } : { span: 24 }"
            v-for="item in disposalTypeList"
            :key="item.id"
          >
            <el-form-item :label="item.name + ':'">
              <div style="width: 95%; display: inline-block">
                <formContent
                  :type="item.type"
                  :disabled="type == 'detail'"
                  v-model="item.value"
                />
              </div>

              <el-link
                type="danger"
                :underline="false"
                v-if="type != 'detail'"
                icon="el-icon-delete"
                style="display: inline-block"
                @click.native="delInfoDisposal(item.id)"
              >
              </el-link>
            </el-form-item>
          </el-col> </el-row
      ></el-form>
    </el-form>

    <template v-slot:footer>
      <el-button @click="cancel">取消</el-button>

      <el-button
        type="primary"
        @click="save"
        :loading="loading"
        v-if="type != 'detail'"
      >
        保存
      </el-button>
      <el-button type="primary" @click="isTemplate = true">
        储存为模板
      </el-button>
    </template>

    <!-- 选择产品 -->

    <MaterialAdd ref="materialAddRef" @chooseEquipment="confirmChoose">
    </MaterialAdd>
    <ele-modal :visible.sync="infoDisposalVisible" width="50vw" append-to-body>
      <infoDisposalList
        :isModal="true"
        :disabledList="form.detailList"
        ref="infoDisposal"
      ></infoDisposalList>
      <template v-slot:footer>
        <el-button @click="infoDisposalVisible = false">取消</el-button>

        <el-button type="primary" @click="getInfoDisposalList">
          确认
        </el-button>
      </template>
    </ele-modal>
    <ele-modal :visible.sync="isTemplate" width="500px" append-to-body>
      <el-form label-width="100px" class="create-form">
        <el-col v-bind="styleResponsive ? { lg: 24, md: 24 } : { span: 24 }">
          <el-form-item label="模板名称:" prop="templateName">
            <el-input v-model="templateName" />
          </el-form-item>
        </el-col>
      </el-form>
      <template v-slot:footer>
        <el-button @click="isTemplate = false">取消</el-button>

        <el-button type="primary" @click="addTemplate"> 确认 </el-button>
      </template>
    </ele-modal>
    <templateList ref="templateList" @success="getTemplateList"></templateList>

    <Detail
      v-if="activeComp === 'bpm' && form.processInstanceId"
      :id="form.processInstanceId"
    ></Detail>
  
  </ele-modal>
</template>

<script>
// import AssetsDialog from './AssetsDialog.vue';
import MaterialAdd from '@/views/maintenance/components/MaterialAdd.vue';
import templateList from './templateList.vue';
import Detail from '@/views/processInstance/detail.vue';

import infoDisposalList from '@/views/equipmentDisposal/infoDisposal/index.vue';
import { save, saveTemplate, bpmPage } from '@/api/equipmentDisposal/index.js';
import formContent from '@/views/equipmentDisposal/infoDisposal/formContent.vue';
const defForm = {
  name: '',
  id: '', //维修工单id
  disposalType: '',
  managementCategory: '',
  code: '',
  disposalTypeList: [],
  deviceList: []
};
export default {
  components: {
    // AssetsDialog,
    MaterialAdd,
    infoDisposalList,
    Detail,
    templateList,
    formContent,
    // workList
  },
  data() {
    return {
      activeComp: 'main',
      tabOptions: [
        { key: 'main', name: '处置详情' },
        { key: 'bpm', name: '流程详情' }
      ],
      visible: false,
      loading: false,
      isTemplate: false,
      infoDisposalVisible: false,
      title: '物品处置',
      type: '',
      form: { ...defForm },
      rules: {
        name: [{ required: true, message: '请选择', trigger: 'change' }],
        type: [{ required: true, message: '请选择', trigger: 'change' }],

        disposalType: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      deviceList: [],
      disposalTypeList: [],
      columns: [],
      templateName: '',
    };
  },

  computed: {
    // 是否开启响应式布局
    styleResponsive() {
      return this.$store.state.theme.styleResponsive;
    }
  },

  methods: {
    async columnsInit(type) {
      this.columns = [
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'fixCode',
          label: '固资编码',
          showOverflowTooltip: true,
          width: 100,
          fixed: 'left',
          align: 'center'
        },
        {
          prop: 'codeNumber',
          label: '编码',
          width: 100,
          fixed: 'left',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'name',
          width: 120,
          fixed: 'left',
          showOverflowTooltip: true,
          label: '名称',
          align: 'center'
        },

        {
          prop: 'modelType',
          showOverflowTooltip: true,
          slot: 'modelType',
          label: '型号',
          align: 'center'
        },
        {
          prop: 'specification',
          showOverflowTooltip: true,
          slot: 'specification',
          label: '规格',
          align: 'center'
        },
        {
          prop: 'sealingTime',
          showOverflowTooltip: true,
          label: '封存时间',
          show: type == 6,
          align: 'center'
        },
        {
          showOverflowTooltip: true,
          prop: 'postName',
          label: '使用部门',
          align: 'center'
        },
        {
          prop: 'usePerson',
          showOverflowTooltip: true,
          label: '使用人',
          align: 'center'
        },
        {
          prop: 'serviceLife',
          label: '耐用年限',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'alreadyServiceLife',
          label: '已使用年限',
          showOverflowTooltip: true,
          align: 'center'
        },

        {
          prop: 'originalValue',
          label: '原值',
          slot: 'originalValue',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'netWorth',
          slot: 'netWorth',
          label: '净值',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          slot: 'scrapValue',
          prop: 'scrapValue',
          label: '残值',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'manufacturer',
          label: '生产厂家',
          showOverflowTooltip: true,
          align: 'center'
        },

        {
          prop: 'pathName',
          label: '位置',
          showOverflowTooltip: true,
          minWidth: 110,
          formatter: (_row) => {
            const positionDetail =
              _row.position &&
              _row.position.length != 0 &&
              _row.position[0].detailPosition
                ? _row.position[0].detailPosition
                : '-';
            return _row.deviceLocationName
              ? _row.deviceLocationName + '-' + positionDetail
              : '';
          },

          align: 'center'
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 140,
          align: 'center',
          resizable: false,
          fixed: 'right',
          slot: 'action',
          showOverflowTooltip: true
        }
      ];
    },
    async open(row, type) {
      this.activeComp = 'main';

      this.type = type;

      if (type != 'add') {
        this.form = JSON.parse(JSON.stringify(row));
        this.form.disposalType = this.form.disposalType + '';
        this.form.managementCategory = this.form.managementCategory + '';
        this.deviceList = this.form.deviceList;
        this.disposalTypeList = this.form.disposalTypeList;
      }
      this.columnsInit(this.form.disposalType);
      this.visible = true;
    },
    disposalTypeChange(val) {
      this.columnsInit(val);
    },
    del(id) {
      this.deviceList = this.deviceList.filter((item) => item.id != id);
    },
    cancel() {
      this.form = { ...defForm };
      this.deviceList = [];
      this.disposalTypeList = [];
      console.log(this.deviceList, 'this.deviceList');
      this.visible = false;
    },

    addEquipment() {
      if (!this.form.disposalType) {
        this.$message.error('请选择处置方式');
        return;
      }
      this.$refs.materialAddRef.open(null, null, true, this.deviceList,this.form.disposalType);
    },
    // 确定选择
    confirmChoose(data) {
      this.deviceList.push(...data);
    },
    getInfoDisposalList() {
      this.disposalTypeList.push(...this.$refs.infoDisposal.getValue());
      this.infoDisposalVisible = false;
    },
    delInfoDisposal(id) {
      this.disposalTypeList = this.disposalTypeList.filter(
        (item) => item.id != id
      );
    },
    changeTemplateList() {
      this.$refs.templateList.open();
    },
    getTemplateList(data) {
      this.form = JSON.parse(JSON.stringify(data.templateList[0]));
      this.deviceList = this.form.deviceList;
      this.disposalTypeList = this.form.disposalTypeList;
    },
    async addTemplate() {
      if (!this.templateName) {
        this.$message.error('模板名称不能为空');
      }
      let data = JSON.parse(JSON.stringify(this.form));
      data.deviceList = this.deviceList;
      data.disposalTypeList = this.disposalTypeList;
      ['id', 'code', 'approvalStatus', 'createTime'].forEach((key) => {
        delete data[key];
      });
      await saveTemplate({
        name: this.templateName,
        type: data.disposalType,
        templateList: [data]
      });

      this.isTemplate = false;
    },
    /* 保存编辑 */
    async save() {
      if (this.deviceList.length == 0) {
        this.$message.error('请选择处置对象！');
        return;
      }

      this.form.deviceList = this.deviceList;
      this.form.disposalTypeList = this.disposalTypeList;
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          save(this.form)
            .then((res) => {
              this.loading = false;
              this.$message.success('成功');
              this.cancel();
              this.$emit('refresh');
            })
            .catch((e) => {
              this.loading = false;
            });
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.basic-details-title {
  margin: 10px 0;
}
.title {
  font-size: 16px;
  line-height: 45px;
}
.add-product {
  width: 100%;
  display: flex;
  align-items: center;
  // justify-content: flex-end;
  font-size: 30px;
  color: #1890ff;
  margin: 10px 0;
  cursor: pointer;
}
</style>
