<template>
  <div>
    <el-card class="el-card">
      <el-form :model="filterQuery" class="query-form" label-width="100px" v-if="showSearch">
        <el-row>
          <el-col :span="6">
            <el-form-item label="申购单号">
              <el-input v-model="filterQuery.applyBillNo" style="width: 90%" placeholder="请输入申购单号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申购负责人">
              <el-input v-model="filterQuery.createName" style="width: 90%" clearable placeholder="请输入申购负责人">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品名称">
              <el-input v-model="filterQuery.productName" style="width: 90%" clearable placeholder="请输入产品名称">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="论证状态：" prop="argStatus">
              <el-select v-model="filterQuery.argStatus" placeholder="请选论证状态" style="width: 90%" @change="getList" clearable>
                <el-option label="待论证" :value=0></el-option>
                <el-option label="论证通过" :value=1></el-option>
                <el-option label="论证拒绝" :value=2></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div class="top-right-btn">
        <el-button-group style="display:flex;">
          <el-button icon="el-icon-view" type="primary" @click="hideSearch">显示/隐藏搜索栏</el-button>
          <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="onSubmitFind">查询</el-button>
          <el-button type="primary" icon="el-icon-printer" @click="optinPrint">选中打印</el-button>
          <el-button type="primary" icon="el-icon-printer" @click="selectPrint">查询结果打印</el-button>

        </el-button-group>
      </div>
      <el-divider style="margin: 15px"></el-divider>

      <el-table v-loading="loading" :data="list" style="width: 100%" border highlight-current-row @selection-change="handleCheckedChange" >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column label="申购单号" prop="applyBillNo"></el-table-column>
        <el-table-column label="申购仓库" prop="invCode" :formatter="invCodeFormat"></el-table-column>
        <el-table-column label="申购负责人" prop="createName"></el-table-column>
        <el-table-column label="所属部门" prop="deptName"></el-table-column>
        <el-table-column label="产品名称" prop="productName"></el-table-column>
        <el-table-column label="数量" prop="count"></el-table-column>
        <el-table-column label="单位" prop="measname"></el-table-column>

        <el-table-column label="论证状态" prop="argStatus" >
          <template slot-scope="scope" >
            <el-tag :type="(scope.row.argStatus) | statusFilterType" >
              {{ statusMap[(scope.row.argStatus)] }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.native="openArg(scope.$index, scope.row)"  v-if="scope.row.argStatus == 0">填写论证</el-button>
            <el-button type="text" size="small" @click.native="openArg(scope.$index, scope.row)"  v-if="scope.row.argStatus != 0">查看论证</el-button>
<!--            <el-button type="text" size="small" @click.native="printArg(scope.$index, scope.row)"  v-if="scope.row.argStatus == 1">打印</el-button>-->
          </template>
        </el-table-column>
      </el-table>


      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="filterQuery.page"
        :limit.sync="filterQuery.limit"
        @pagination="handleCurrentChange"

      ></pagination>
    </el-card>

    <el-dialog
      :title="formMap[formName]"
      :visible.sync="argVisible"
      width="65%"
      v-if="argVisible"
      @close='closeDialog'
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <el-form :model="row" :rules="formRules" ref="dataForm" label-width="100px" :disabled="row.argStatus != 0" >
        <el-row type="flex" justify="end">
          <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px;margin-top: -10px">
            <el-button type="danger" @click.native="saveArg(2)" :loading="loading" v-show="row.argStatus == 0">论证拒绝</el-button>
            <el-button type="success" @click.native="saveArg(1)" :loading="loading"  v-show="row.argStatus == 0">论证通过</el-button>
          </el-button-group>
        </el-row>

        <el-card style="margin-top: -5px;">
          <el-row>
            <el-col :span="11">
              <el-form-item label="申报科室：" prop="deptName">
                <el-input v-model="row.deptName" style="width: 90%" auto-complete="off" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="申购负责人：" prop="createName">
                <el-input v-model="row.createName" style="width: 90%" auto-complete="off" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="仪器名称：" prop="productName">
                <el-input v-model="row.productName"   auto-complete="off" style="width: 90%" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="数量：" prop="count">
                <el-input v-model="row.count" style="width: 90%" auto-complete="off" :disabled="true"></el-input>
                <span style="margin-left: 10px;">{{ row.measname || '' }}</span>
              </el-form-item>

            </el-col>
          </el-row>

          <el-row>
          <el-col :span="22">
            <el-form-item label="配置要求及主要技术参数：" prop="mainParam">
              <el-input v-model="row.mainParam"
                        auto-complete="off"
                        style="width: 95%; resize: vertical;"
                        type="textarea"
                        :rows="6" > </el-input>
            </el-form-item>
          </el-col>
          </el-row>

          <el-row>
            <el-col :span="22">
              <el-form-item label="申请理由：" prop="applicationReason">
                <el-input v-model="row.applicationReason" auto-complete="off"
                          style="width: 95%; resize: vertical;"
                          type="textarea"
                          :rows="4" > </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="22">
              <el-form-item label="效益预测：" prop="supportCondition">
                <el-input v-model="row.supportCondition" auto-complete="off"
                          style="width: 95%; resize: vertical;"
                          type="textarea"
                          :rows="5" > </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="22">
              <el-form-item label="使用科室人员配备情况：" prop="supportPerson">
                <el-input v-model="row.supportPerson" auto-complete="off"
                          style="width: 95%; resize: vertical;"
                          type="textarea"
                          :rows="5" > </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="22">
              <el-form-item label="维修技术力量的保证或维修途径：" prop="maintenanceForce">
                <el-input v-model="row.maintenanceForce" auto-complete="off"
                          style="width: 95%; resize: vertical;"
                          type="textarea"
                          :rows="5" > </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="22">
              <el-form-item label="资金来源：" prop="fundSource">
<!--                <el-input v-model="row.fundSource" auto-complete="off"-->
<!--                          style="width: 95%; resize: vertical;"-->
<!--                          type="textarea"-->
<!--                          :rows="2" > </el-input>-->

                <el-checkbox-group v-model="fundSource">
                  <el-checkbox label="医院自有经费" value="医院自有经费">医院自有经费</el-checkbox>
                  <el-checkbox label="财政补助" value="财政补助">财政补助</el-checkbox>
                  <el-checkbox label="科研经费" value="科研经费">科研经费</el-checkbox>
                  <el-checkbox label="其他" value="其他">其他</el-checkbox>
                  <!-- 更多的资金来源选项 -->
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="22">
              <el-form-item label="可行性论证：" prop="feasibility">
                <el-input v-model="row.feasibility" auto-complete="off"
                          style="width: 95%; resize: vertical;"
                          type="textarea"
                          :rows="5" > </el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-card>
      </el-form>

    </el-dialog>


  </div>
</template>
<script>

import {list,updateArg,printArg} from "@/api/purchase/purApplyArgument";
import {findInvByUser} from "@/api/system/invSubWarehouse";
import {
  verifyTemplateFile
} from '@/api/inout/orderDetailResult'

export default {
  name: "purApplyArgument",
  data() {
    return {
      pageType:null,
      fundSource: [], // 初始化为空数组，用于存储用户选择的资金来源
      defaultSort: {prop: 'createTime', order: 'desc'},
      showSearch: true,
      pId: null,
      isChang: false,
      filterQuery: {
        applyBillNo: "",
        argStatus: null,
        createName: "",
        productName: "",
        deptCode: null,
        pageType: this.pageType,
        page: 1,
        limit: 10,
      },
      invCodebe: null,
      formName: null,
      orderSelection: [],
      formMap: {
        update: "填写论证",
        select: "论证详情",
      },
      statusMap: {
        0: "待论证",
        1: "通过",
        2: "拒绝"
      },
      typeList:[
        {name: '战略' ,code: 1 },
        {name: '长期' ,code: 2 },
        {name: '短期' ,code: 3 }
      ],
      statusList:[
        {name: '草稿' ,code: 1 },
        {name: '未审核' ,code: 2 },
        {name: '已审核' ,code: 3 }
      ],
      payTypeList:[
        {name: '银行' ,code: 1 },
        {name: '微信' ,code: 2 },
        {name: '支付宝' ,code: 3}
      ],
      idQuery: {},
      row: {},
      total: 0,
      thirdSys: [],
      thirdSysDetail: null,
      busTypes: [],
      originTypes: [],
      list: [],
      detailList: [],
      loading: false,
      actDateRange: [],
      emergencyMap: {
        1: "正常",
        2: "较急",
        3: "特急",
      },
      detailquery:
        {
          orderIdFk: null,
          total: 0,
          page: 1,
          limit: 10,
        },
      invList: {},
      deptList: {},
      argVisible: false,
      newDistributionFormPlanVisible: false,
      approvalFlowDetailVisible: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },

  methods: {

    invCodeFormat(row) {
      let obj = ''
      this.invList.forEach((item) => {
        //循环list，如果数据相等return出去就好了
        //不会影响原来的数据，只是展示出来的是name
        if (row.invCode == item.code) {
          obj = item.name
        }
      })
      return obj
    },
    statusFormat(row) {
      let obj = ''
      this.statusList.forEach((item) => {
        //循环list，如果数据相等return出去就好了
        //不会影响原来的数据，只是展示出来的是name
        if (row.status == item.code) {
          obj = item.name
        }
      })
      return obj
    },
    typeFormat(row) {
      let obj = ''
      this.typeList.forEach((item) => {
        //循环list，如果数据相等return出去就好了
        //不会影响原来的数据，只是展示出来的是name
        if (row.type == item.code) {
          obj = item.name
        }
      })
      return obj
    },
    payTypeFormat(row) {
      let obj = ''
      this.payTypeList.forEach((item) => {
        //循环list，如果数据相等return出去就好了
        //不会影响原来的数据，只是展示出来的是name
        if (row.payType == item.code) {
          obj = item.name
        }
      })
      return obj
    },
    onReset() {
      this.filterQuery = {
        applyBillNo: "",
        argStatus: null,
        createName: "",
        productName: "",
        deptCode: null,
        pageType: this.pageType,
        page: 1,
        limit: 10,
      };
      this.getList();
    },
    handleClose() {
      this.argVisible = false;
      this.getList();
    },
    getId(id) {
      if (this.formName == 'add' && id != null) {
        var data = {
          id: id
        }
        this.pId = id;
        //当在新增时取消添加操作删除掉这次的数据
        delContractDetailAll(data).then((response) => {
          if (response.code == 20000) {
            this.newSpDistributionVisible = false
          }
        });
      } else {
        this.newSpDistributionVisible = false
      }

    },
    onSubmitFind() {
      this.filterQuery.page = 1;
      this.getList();
    },
    hideSearch() {
      this.showSearch = !this.showSearch;
    },

    handleSortChange(column, prop, order) {
      if (column.order === 'descending') {
        this.filterQuery.sort = 'desc'
      } else {
        this.filterQuery.sort = 'asc'
      }
      this.filterQuery.orderBy = column.prop;
      this.getList();
    },


    getList() {
      this.loading = true;
      list(this.filterQuery).then((response) => {
        if (response.code == 20000) {
          this.list = response.data.list || [];
          this.total = response.data.total || 0;
          this.detailList = []
        } else {
          this.$message.error(response.message);
        }
        this.loading = false;
      })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },
    submitOrder(row) {
      this.$confirm("是否确定提交审核?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          let tQuery = {
            editStatus: 2,
            purPlanEntity: row,
          }
          inserThrOrderWeb(tQuery)
            .then(response => {
              this.loading = false;
              if (response.code === 20000) {
                this.$message.success("提交成功！");
                this.getList();
              } else {
                this.$message.error(response.message);
              }
            })
            .catch(() => {
              this.loading = false;
            })
        })
        .catch(() => {
        });
    },

    handleCurrentChange(val) {
      this.filterQuery.page = val.page;
      this.getList();
    },
    handleCurrentChangeDetail(val) {
      this.detailquery.page = val.page;
      this.handleDetail(this.row)
    },
    closeDialog() {
      this.argVisible = false;
      this.getList();
    },
    closeDialogSp() {
      this.newDistributionFormPlanVisible = false;
      this.getList();
    },
    getInvList() {
      let query = {};
      this.invList = [];
      findInvByUser(query)
        .then((response) => {
          this.invList = response.data || [];
        })
        .catch(() => {
        });
    },

    openArg(index, row) {
      this.row = row
      if (row.argStatus != 0){
        this.formName = "select";
      }else {
        this.formName = "update";
      }
      if (this.row.fundSource != null && this.row.fundSource != ''){
        this.fundSource = this.row.fundSource.split('、'); // 使用逗号加空格作为分隔符
      }else {
        this.fundSource = [];
      }

      this.argVisible = true;
    },
    handleCheckedChange(val) {
      this.orderSelection = val;
    },
      optinPrint() {
        this.$confirm("是否确定打印选中论证单据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
            if (this.orderSelection == null || this.orderSelection.length <= 0) {
              return this.$message.error("请选择打印的明细！");
            }

            let query = { id: 7 }
            verifyTemplateFile(query).then((res) => {
              if (res.code === 20000) {
                let printParams = {
                  applyBillNo: this.filterQuery.applyBillNo,
                  argStatus: this.filterQuery.argStatus,
                  createName: this.filterQuery.createName,
                  productName: this.filterQuery.productName,
                  deptCode: this.filterQuery.deptCode,
                  pageType: this.filterQuery.pageType,
                  list: this.orderSelection,
                  templateId: res.data
                }
            printArg(printParams).then((response) => {
              //将pdf文件转换为url。
              const binaryData = [];
              binaryData.push(response);
              //获取blob链接。
              let url = window.URL.createObjectURL(
                new Blob(binaryData, {type: "application/pdf"})
              );
              this.loading = false;
              window.open(url);//打开新标签页，预览pdf。
            })
              } else {
                return this.$message.error('摸版错误！')
              }
          }).catch((error) => {
          this.loading = false;
        })
        })
      },
      selectPrint() {
        this.$confirm("是否确定打印所有查询结果数据", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {

          let query = { id: 7 }
          verifyTemplateFile(query).then((res) => {
            if (res.code === 20000) {
              let printParams = {
                applyBillNo: this.filterQuery.applyBillNo,
                argStatus: this.filterQuery.argStatus,
                createName: this.filterQuery.createName,
                productName: this.filterQuery.productName,
                deptCode: this.filterQuery.deptCode,
                pageType: this.filterQuery.pageType,
                templateId: res.data
              }

          printArg(printParams).then((response) => {
              //将pdf文件转换为url。
              const binaryData = [];
              binaryData.push(response);
              //获取blob链接。
              let url = window.URL.createObjectURL(
                new Blob(binaryData, {type: "application/pdf"})
              );
              this.loading = false;
              window.open(url);//打开新标签页，预览pdf。
          })
          } else {
                return this.$message.error('摸版错误！')
              }
            }).catch((error) => {
            this.loading = false;
          })
        })
        return;

      },

    },

    saveArg(argStatus){
        if (this.fundSource.length > 0){
          this.row.fundSource = this.fundSource.join('、'); // 使用逗号加空格作为分隔符
        }
        this.row.argStatus = argStatus;
        //提交 update
        updateArg(this.row).then(response => {
          this.loading = false;
          if (response.code === 20000) {
            this.$message.success("提交成功！");
            this.getList();
            this.argVisible = false;
          } else {
            this.$message.error(response.message);
          }
        })

  }
  ,
  components: {

  }
  ,
  filters: {
    statusFilterType(status) {
      const statusMap = {
        0: "warning",
        1: "success",
        2: "danger"
      };
      return statusMap[status];
    }
    ,
  }
  ,
  mounted() {
  }
  ,
  created() {
    this.getList();
    this.getInvList();
    this.pageType = this.$route.query.pageType;
  }
  ,
}
;
</script>
<style scoped>
.itemTag {
  float: left;
  text-align: left;
  margin-top: 10px;
  width: 25%;
}

.text {
  font-size: 13px;
  font-family: "Microsoft YaHei";
}


.el-row {
  display: flex;
  flex-wrap: wrap;
}

.el-col {
  border-radius: 4px;
  flex-wrap: wrap;
}
/* 样式模拟自动调整高度（不完全自动，但可以通过resize属性让用户手动调整） */
.el-textarea__inner {
  min-height: 50px; /* 设置最小高度 */
  transition: height 0.3s ease; /* 添加过渡效果 */
  /* 其他你需要的样式 */
}
</style>

