<template>
  <div class="druglist">
    <!-- 顶部筛选 -->
    <div class="screening">
      <div class="screening-title flex-vertical-center-l">
        <img src="~@/assets/filters.png" alt />
      </div>
      <div class="screening-form flex-vertical-center-l flex-wrap">
        <div class="screening-item flex-vertical-center-l">
          <span>映射状态：</span>
          <div class="input">
            <el-select
              size="mini"
              placeholder="全部"
              v-model="searchData.isMapping"
              clearable
            >
              <el-option :value="0" label="未映射"></el-option>
              <el-option :value="1" label="已映射"></el-option>
            </el-select>
          </div>
        </div>
        <div class="screening-item flex-vertical-center-l">
          <span>平台非药物疗法：</span>
          <div class="input">
            <el-input
              size="mini"
              placeholder="请输入二级分类名称"
              v-model="searchData.secondName"
              @keydown.enter.native="search()"
              clearable
            ></el-input>
          </div>
        </div>

        <el-button type="primary" size="mini" @click="search()">搜索</el-button>
        <el-button type="warning" size="mini" @click="clearFilter()"
          >清空</el-button
        >
        <div style="width: 60px;"></div>
        <el-button type="warning" size="mini" @click="$router.back()"
          >返回</el-button
        >
        <el-button type="primary" size="mini" @click="autoMap"
          >自动映射</el-button
        >
        <el-button type="danger" size="mini" @click="clearMap"
          >清空映射</el-button
        >
      </div>
    </div>

    <!-- 底部表格数据 -->
    <div class="table">
      <div class="today-table">
        <div class="table-container">
          <el-table
            :data="tableData"
            v-loading="loading"
            stripe
            style="width: 100%"
            border
            height="100%"
            :header-cell-style="headerCellStyle"
          >
            <el-table-column
              type="index"
              label="序号"
              width="60"
              align="center"
              :index="indexMethod"
            ></el-table-column>
            <el-table-column label="平台非药物疗法">
              <el-table-column
                label="一级分类"
                prop="firstLevel"
                align="center"
              >
                <template slot-scope="scope">
                  <span
                    :style="{
                      color: String(scope.row.isMapping) !== '1' ? 'red' : '',
                    }"
                    >{{ scope.row.firstLevel || "-" }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column
                label="二级分类"
                prop="secondLevel"
                align="center"
              >
                <template slot-scope="scope">
                  <span
                    :style="{
                      color: String(scope.row.isMapping) !== '1' ? 'red' : '',
                    }"
                    >{{ scope.row.secondLevel || "-" }}</span
                  >
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="第三方非药物疗法">
              <el-table-column label="项目名称" align="center">
                <template slot-scope="scope">
                  <el-select
                    v-if="activeEditIndex === scope.$index"
                    size="mini"
                    :loading="editData[scope.$index].loading"
                    :placeholder="editData[scope.$index].placeholder"
                    filterable
                    remote
                    :remote-method="matSearchRemoteMethod"
                    v-model="editData[scope.$index].matDrugId"
                    @change="onSelectChange(scope.$index, $event)"
                    @focus="focusEditRow(scope.$index)"
                    @visible-change="onVisibleChange(scope.$index, $event)"
                  >
                    <el-option
                      v-for="option in editData[scope.$index].options"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                    />
                  </el-select>
                  <div
                    v-else
                    class="clickable-name"
                    @click="activateEdit(scope.$index)"
                  >
                    {{
                      editData[scope.$index]
                        ? editData[scope.$index].displayName || "-"
                        : "-"
                    }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="编码" width="150" align="center">
                <template slot-scope="scope">
                  <div>{{ scope.row.itemCode || "-" }}</div>
                </template>
              </el-table-column>
              <el-table-column label="计价单位" width="100" align="center">
                <template slot-scope="scope">
                  <div>{{ scope.row.pricingUnit || "-" }}</div>
                </template>
              </el-table-column>
              <el-table-column label="价格" width="100" align="center">
                <template slot-scope="scope">
                  <div>{{ scope.row.price || "-" }}</div>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex-vertical-center-r today-page">
          <div></div>
          <el-pagination
            background
            layout=" prev, pager, next, jumper, total"
            :total="total"
            :page-size="limit"
            @current-change="sizeC($event)"
          ></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import popup from "@/components/Propup.vue";
import {
  getNondrugMapList,
  autoMapNondrug,
  clearMapNondrug,
  materialQuery,
  manualMapping,
} from "@/api/nonDrug.js";
import { mapGetters } from "vuex";

export default {
  components: {
    popup,
  },
  data() {
    return {
      searchData: {
        pid: "",
        appId: "",
        deptId: "",
        institutionCode: "",
        isMapping: "",
        secondName: "",
      },
      loading: false,
      tableData: [],
      page: 1,
      limit: 10,
      total: 0,

      editIndex: -1,
      activeEditIndex: -1,
      editData: [],
      editOriginalMatDrugId: "",
      changeHandled: false,
    };
  },
  activated() {
    this.load();
  },
  methods: {
    async load() {
      this.activeEditIndex = -1;
      this.searchData = {
        pid: this.$route.query.pid || "",
        appId: this.$route.query.ygtid || "",
        deptId: this.$route.query.departmentidSelsource || "",
        institutionCode: this.$route.query.stitutionsId || "",
        isMapping: "",
        secondName: "",
      };
      this.page = 1;
      await this.getList();
    },
    sizeC(e) {
      this.page = e;
      this.getList();
    },
    search() {
      this.page = 1;
      this.getList();
    },
    async clearFilter() {
      this.searchData = {
        pid: this.$route.query.pid || "",
        appId: this.$route.query.ygtid || "",
        deptId: this.$route.query.departmentidSelsource || "",
        institutionCode: this.$route.query.stitutionsId || "",
        isMapping: "",
        secondName: "",
      };
      this.page = 1;
      this.getList();
    },
    async getList() {
      this.loading = true;
      try {
        const {
          appId,
          deptId,
          institutionCode,
          isMapping,
          secondName,
        } = this.searchData;
        let params = {
          appId,
          deptId,
          institutionCode,
          isMapping,
          secondName,
          pageNum: this.page,
          pageSize: this.limit,
        };
        let res = await getNondrugMapList(params);
        if (res.ResultCode == 0) {
          const data = res.Data || {};
          this.tableData = data.Items || [];
          this.total = data.TotalRecordCount || 0;
        } else throw { message: res.ResultInfo };
        this.initEditData();
      } catch (e) {
        this.$message.error(e.message);
      }
      this.loading = false;
    },
    initEditData() {
      this.editData = this.tableData.map((item) => {
        const isMapped = String(item.isMapping) === "1";
        const displayName = isMapped ? item.itemName || "-" : "-";
        return {
          id: item.id,
          matDrugId: isMapped ? item.id : "",
          matDrugName: item.itemName || "",
          matDrugDw: item.pricingUnit || "",
          displayName,
          loading: false,
          placeholder: displayName !== "-" ? displayName : "请输入项目名称搜索",
          options: isMapped
            ? [{ value: item.id, label: item.itemName, dw: item.pricingUnit }]
            : [],
        };
      });
    },
    focusEditRow(index) {
      this.editIndex = index;
      const item = this.editData[index];
      let name = "";
      if (item.matDrugName) {
        try {
          name = item.matDrugName.match(/[\u4E00-\u9FFF]+/g)[0];
        } catch (e) {
          name = "";
        }
      }
      this.matSearchRemoteMethod(name || " ", index);
    },
    activateEdit(index) {
      this.activeEditIndex = index;
      this.editOriginalMatDrugId = this.editData[index].matDrugId;
      this.changeHandled = false;
    },
    async onSelectChange(index, value) {
      this.changeHandled = true;
      this.updateEditRow(index, value);
      await this.doManualMapping(index);
      this.activeEditIndex = -1;
    },
    onVisibleChange(index, visible) {
      if (visible) return;
      if (this.changeHandled) return;
      if (this.editData[index].matDrugId !== this.editOriginalMatDrugId) {
        this.doManualMapping(index);
      }
      this.activeEditIndex = -1;
    },
    async doManualMapping(index) {
      try {
        const row = this.tableData[index];
        const item = this.editData[index];
        let params = {
          deptId: this.searchData.deptId,
          firstName: row.firstLevel || "",
          organizationid: this.searchData.appId,
          platformClassifyId: row.id || "",
          secondName: row.secondLevel || "",
          sititutionNondrugId: item.matDrugId || "",
          sititutionid: this.searchData.institutionCode,
        };
        const loading = this.$loading({
          lock: true,
          text: "正在映射",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        const res = await manualMapping(params).catch((err) => {
          loading.close();
        });
        if (res.ResultCode == 0) {
          loading.close();
          this.$message.success("映射保存成功");
          await this.getList();
        }
      } catch (e) {
        this.$message.error(e.message);
      }
    },
    updateEditRow(index, value) {
      const item = this.editData[index];
      if (value) {
        const option = item.options.find((o) => o.value === value);
        item.displayName = option.label;
        item.matDrugName = option.label;
        item.matDrugDw = option.dw || "";
      } else {
        item.displayName = "-";
        item.matDrugName = "";
        item.matDrugDw = "";
      }
    },
    async matSearchRemoteMethod(name, index) {
      if (index == null) index = this.editIndex;
      const item = this.editData[index];
      if (!name) {
        item.options = item.matDrugId
          ? [{ value: item.matDrugId, label: item.matDrugName }]
          : [];
      } else {
        item.loading = true;
        item.options = await materialQuery({
          name: name.trim(),
          appId: this.searchData.appId,
          deptId: this.searchData.deptId,
          institutionCode: this.searchData.institutionCode,
        })
          .then((res) => {
            if (res.ResultCode === 0)
              return (res.Data || []).map((d) => ({
                value: d.pid,
                label: d.itemName || d.name,
                dw: d.pricingUnit || d.dw,
              }));
            return [];
          })
          .catch(() => []);
        item.loading = false;
      }
      return item.options;
    },
    // 自动映射
    autoMap() {
      this.$confirm("确认自动映射所有未映射的非药物疗法？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await autoMapNondrug({
              basisNondrugcatalogueId: this.searchData.pid,
            });
            if (res.ResultCode == 0) {
              this.$message.success("自动映射成功");
              this.getList();
            }
          } catch (e) {
            this.$message.error(e.message);
          }
        })
        .catch(() => {});
    },
    // 清空映射
    clearMap() {
      this.$confirm("确认清空本列表的全部映射关系吗？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await clearMapNondrug({
              basisNondrugcatalogueId: this.searchData.pid,
            });
            if (res.ResultCode == 0) {
              this.$message.success("清空映射成功");
              this.getList();
            } 
          } catch (e) {
            this.$message.error(e.message);
          }
        })
        .catch(() => {});
    },
    indexMethod(index) {
      return (this.page - 1) * this.limit + index + 1;
    },
    headerCellStyle({ rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        // 序号列
        if (columnIndex === 0) return { backgroundColor: "#f3fffb" };
        // 平台非药物疗法
        if (columnIndex === 1) return { backgroundColor: "#efe1c7" };
        // 第三方非药物疗法
        if (columnIndex === 2) return { backgroundColor: "#c7efef" };
      }
      if (rowIndex === 1) return { backgroundColor: "#c7efef" };
      return {};
    },
  },
  computed: {
    ...mapGetters(["getuserinfo"]),
  },
};
</script>
<style lang="scss" scoped>
@import "../../style/common.scss";
@import "../../style/base.scss";

.table {
  padding: 5px 5px;
  background: #ffffff;
  border-radius: 5px;
  margin-top: 10px;
  height: 72vh;

  .flex-vertical-center-r {
    justify-content: space-between;
  }

  .table-container {
    height: 90%;
  }

  .today-table {
    height: 100%;
  }
}

.clickable-name {
  cursor: pointer;
  min-height: 28px;
  line-height: 28px;
}

.today-table::v-deep .el-table .cell {
  text-align: center;
}
</style>

<style lang="scss" scoped>
@media screen and (min-width: 1681px) and (max-width: 1920px) {
  .table {
    height: 82vh;

    .table-container {
      height: 94%;
    }
  }

  .today-table::v-deep .el-table td {
    padding: 18px 0;
  }

  .today-table::v-deep .el-table th {
    padding: 18px 0;
  }
}

@media screen and (min-width: 1601px) and (max-width: 1680px) {
  .table {
    height: 81vh;

    .table-container {
      height: 94%;
    }
  }

  .today-table::v-deep .el-table td {
    padding: 18px 0;
  }

  .today-table::v-deep .el-table th {
    padding: 18px 0;
  }
}

@media screen and (min-width: 1361px) and (max-width: 1600px) {
  .table {
    height: 73vh;

    .table-container {
      height: 90%;
    }
  }

  .today-table::v-deep .el-table td {
    padding: 5px 0;
  }

  .today-table::v-deep .el-table th {
    padding: 5px 0;
  }
}

@media screen and(min-width:1281px) and (max-width: 1360px) {
  .table {
    height: 74vh;

    .table-container {
      height: 90%;
    }
  }

  .today-table::v-deep .el-table td {
    padding: 5px 0;
  }

  .today-table::v-deep .el-table th {
    padding: 5px 0;
  }
}
</style>
