<template>
  <div class="app-container">
    <page-header :content="id?'编辑':'添加'"></page-header>
    <el-form label-width="120px" ref="dataForm" :model="dataForm" :rules="dataRules">
      <el-form-item label="检查项目名称" prop="checkItem.itemName">
        <el-input v-model.trim="dataForm.checkItem.itemName" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="是否计算评分" prop="checkItem.isScore" required>
        <el-radio-group v-model="dataForm.checkItem.isScore">
          <el-radio v-for="item in whetherList" :key="item.id" :label="item.id">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所属分类目录" prop="checkItem.patrolTypeId">
        <el-select v-model="dataForm.checkItem.patrolTypeId" class="input-width">
          <el-option v-for="item in classifyList" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="检查项目说明" prop="checkItem.remark">
        <el-input v-model="dataForm.checkItem.remark"
                  style="width: 400px"
                  type="textarea"
                  maxlength="200"
                  show-word-limit
                  :autosize="{ minRows: 4}"></el-input>
      </el-form-item>

      <el-form-item prop="photoPoints" label-width="0">
        <el-button @click="onAdd" type="primary">添加</el-button>
        <el-button @click="onMoveUp" type="primary" plain>上移</el-button>
        <el-button @click="onMoveDown" type="primary" plain>下移</el-button>
        <el-table :data="dataForm.photoPoints" border stripe highlight-current-row ref="table" class="mt10 w900" @row-click="onRowClick">
          <el-table-column label="拍照点" align="center">
            <el-table-column type="index" :index="indexCompute" label="序号" align="center" fixed="left" width="60px"/>
            <el-table-column prop="name" label="名称" align="center" min-width="160px">
               <template v-slot="scope">
                <el-tooltip class="item" effect="dark" content="该项为必填项" placement="bottom">
                  <el-form-item :prop="'photoPoints.' + scope.$index + '.name'" label-width="0" required>
                    <el-input v-model.trim="scope.row.name" size="small"></el-input>
                  </el-form-item>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="isRequired" label="必须拍照" align="center" width="106px">
               <template v-slot="scope">
                <el-checkbox v-model="scope.row.isRequired" v-if="selectItem===scope.row"></el-checkbox>
                <div v-else>{{ whetherList.find(item => item.id === scope.row.isRequired).label }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="qualifiedJudge" label="合格判断" align="center" width="160px">
               <template v-slot="scope">
                <el-select v-model="scope.row.qualifiedJudge" v-if="selectItem===scope.row">
                  <el-option v-for="item in qualifiedList" :key="item.id" :label="item.label" :value="item.id"></el-option>
                </el-select>
                <div v-else>{{ qualifiedList.find(item => item.id === scope.row.qualifiedJudge).label }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="qualifiedScore" label="合格评分" align="center" width="120px">
               <template v-slot="scope">
                <el-tooltip class="item" effect="dark" content="该项为必填项" placement="bottom">
                  <el-form-item :prop="'photoPoints.' + scope.$index + '.qualifiedScore'" label-width="0" required>
                    <el-input-number v-model.trim.number="scope.row.qualifiedScore" size="small" class="w100" v-if="selectItem===scope.row" controls-position="right"></el-input-number>
                    <div v-else>{{ scope.row.qualifiedScore }}</div>
                  </el-form-item>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="noQualifiedScore" label="不合格评分" align="center" width="120px">
               <template v-slot="scope">
                <el-tooltip class="item" effect="dark" content="该项为必填项" placement="bottom">
                  <el-form-item :prop="'photoPoints.' + scope.$index + '.noQualifiedScore'" label-width="0" required>
                    <el-input-number v-model.trim.number="scope.row.noQualifiedScore" size="small" class="w100"  v-if="selectItem===scope.row" controls-position="right"></el-input-number>
                    <div v-else>{{ scope.row.noQualifiedScore }}</div>
                  </el-form-item>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="80px">
               <template v-slot="scope">
                <el-link type="danger" icon="el-icon-delete" @click="onDelete(scope.$index)" :disabled="dataForm.photoPoints.length<=1">删除</el-link>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <page-footer showConfirm @confirm="onConfirm" @cancel="onCancel" width="800px"></page-footer>
  </div>
</template>

<script>

import {validateNotEmpty} from "@/utils/validate";

export default {
  name: "inspectionPhotoEdit",
  watch: {
    'dataForm.checkItem.patrolTypeId'(value) {
      const classify = this.classifyList.find(item => item.id === value);
      this.dataForm.checkItem.patrolTypeName = classify && classify.typeName;
    },
    classifyList() {
      const classify = this.classifyList.find(item => item.id === this.dataForm.checkItem.patrolTypeId);
      this.dataForm.checkItem.patrolTypeName = classify && classify.typeName;
    }
  },
  data() {
    return {
      id: undefined, // 数据id
      dataForm: {
        checkItem: {
          itemName: undefined, // 检查项名称
          itemType: 4, // 检查项类别 1选择、2数字、3文本、4拍照
          isRequired: true, // 是否必填
          defaultValue: undefined, // 默认值
          isScore: true, // 是否参与评分
          patrolTypeId: undefined, // 巡检类别id
          patrolTypeName: undefined, // 巡检类别名称
          remark: undefined, // 备注说明
        },
        photoPoints: [] // 选项
      },

      dataRules: {
        'checkItem.itemName': [{validator: validateNotEmpty, errorMessage: "检查项名称不能为空", required: true, trigger: 'blur'}],
        'checkItem.patrolTypeId': [{validator: validateNotEmpty, errorMessage: "巡检类别不能为空", required: true, trigger: 'change'}],
      },

      classifyList: [], // 巡检类别列表
      whetherList: [{id: true, label: "是"}, {id: false, label: "否"}],
      qualifiedList: [{id: true, label: "拍照合格"}, {id: false, label: "拍照不合格"}],
      allowList: [{id: true, label: "允许"}, {id: false, label: "不允许"}],
      defaultPhotoPoint: { // 默认拍照点
        name: undefined, // 拍照点名称
        isRequired: false, // 是否必须拍照
        qualifiedJudge: true, // 合格判定
        qualifiedScore: 0, // 合格评分
        noQualifiedScore: 0, // 不合格评分
        seq: undefined, // 排序
      },

      selectItem: undefined, // 选中的单条记录
    }
  },

  mounted() {
    this.initData();
    if (this.id) {
      this.getDetail(this.id);
    }
    this.onAdd();
  },

  methods: {
    // 表格索引
    indexCompute(index) {
      return index + 1;
    },

    // 初始化数据
    initData() {
      this.id = this.$route.query.id;

      this.$axios.get("/v1/check/item/type/list", {params: {size: 100}}, false).then(data => {
        this.classifyList = data.list;
      });
    },

    // 取消
    onCancel() {
      this.$router.back();
    },

    // 确认
    onConfirm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.id) { // 更新
            this.$axios.put("/v1/check/item/update/photo", this.dataForm).then(() => {
              this.$message.success("更新成功！");
              this.$eventBus.$emit("inspectionPhotoUpdate");
              this.onCancel();
            });
          } else { // 添加
            this.$axios.post("/v1/check/item/add/photo", this.dataForm).then(() => {
              this.$message.success("保存成功！");
              this.$eventBus.$emit("inspectionPhotoAdd");
              this.onCancel();
            });
          }
        }
      });
    },

    getDetail(checkItemId) {
      this.$axios.get(`/v1/check/item/query/photo/${checkItemId}`).then(data => {
        this.dataForm = data;
      });
    },

    // 删除选项
    onDelete(index) {
      this.dataForm.photoPoints.splice(index, 1);
    },

    // 添加
    onAdd() {
      this.dataForm.photoPoints.push({...this.defaultPhotoPoint});
      this.sortOptions();
    },

    // 上移
    onMoveUp() {
      if (this.selectItem && this.selectItem.seq > 0) {
        const temp = {...this.dataForm.photoPoints[this.selectItem.seq - 1]};
        this.$set(this.dataForm.photoPoints, this.selectItem.seq - 1, this.selectItem);
        this.$set(this.dataForm.photoPoints, this.selectItem.seq, temp);
        this.sortOptions();
      }
    },

    // 下移
    onMoveDown() {
      if (this.selectItem && this.selectItem.seq < this.dataForm.photoPoints.length - 1) {
        const temp = {...this.dataForm.photoPoints[this.selectItem.seq + 1]};
        this.$set(this.dataForm.photoPoints, this.selectItem.seq + 1, this.selectItem);
        this.$set(this.dataForm.photoPoints, this.selectItem.seq, temp);
        this.sortOptions();
      }
    },

    // 行点击
    onRowClick(row, column, event) {
      this.selectItem = row;
      this.$refs["table"].setCurrentRow(row);
    },

    // 按表格顺序重新排序
    sortOptions() {
      this.dataForm.photoPoints.forEach((item, index) => item.seq = index);
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  .input-width {
    width: 250px;
  }
}
</style>
