<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv">
      <!-- 搜索条件--程序号 -->
      <div class="filter">
        <label>主程序号：</label>
        <Input class="searchInput" v-model="programNo" />
      </div>
      <!-- 搜索条件--产品名称 -->
      <div class="filter">
        <label>产品名称：</label>
        <Select v-model="productId" clearable filterable class="searchSelect">
          <Option v-for="v in productList" :value="v.id" :key="v.id"
            >{{ v.name }}({{ v.code }})</Option
          >
        </Select>
      </div>
      <!-- 搜索条件--审核状态 -->
      <div class="filter">
        <label>审核状态：</label>
        <Select v-model="auditStatus" clearable class="searchSelect">
          <Option :value="1">待审核</Option>
          <Option :value="2">已审核</Option>
          <Option :value="3">被拒绝</Option>
        </Select>
      </div>
      <!-- 按钮组 -->
      <div class="searchBtn">
        <!-- 查询 -->
        <Button
          v-if="btnShow1"
          type="primary"
          class="twoWord"
          icon="ios-search"
          @click="search(true)"
        >
          查询
        </Button>
        <!-- 创建 -->
        <Button
          v-if="btnShow2"
          type="success"
          class="twoWord"
          icon="md-add-circle"
          @click="add()"
        >
          创建
        </Button>
        <!-- 修改 -->
        <Button
          v-if="btnShow3"
          type="warning"
          class="twoWord"
          icon="ios-create-outline"
          @click="edit()"
        >
          修改
        </Button>
        <!-- 删除 -->
        <Button
          v-if="btnShow4"
          type="error"
          class="twoWord intervalRight"
          icon="md-close-circle"
          @click="del()"
        >
          删除
        </Button>
        <!-- 编辑 -->
        <Button
          v-if="btnShow5"
          type="primary"
          class="twoWord"
          icon="md-create"
          @click="editProgram()"
        >
          编辑
        </Button>
        <!-- 下载 -->
        <Button
          v-if="btnShow6"
          type="primary"
          class="twoWord"
          icon="md-download"
          @click="download()"
        >
          下载
        </Button>
        <!-- 版本记录 -->
        <Button
          v-if="btnShow7"
          type="primary"
          class="fourWord"
          icon="md-recording"
          @click="getHistory()"
        >
          版本记录
        </Button>
      </div>
    </div>
    <div class="divborder newTableDiv">
      <!-- 表格 -->
      <Table
        highlight-row
        class="tableClass"
        :data="tableData"
        :columns="tableColumns"
        @on-current-change="handleRowChange"
      >
      </Table>
      <!-- 分页器 -->
      <div class="pageDiv">
        <div class="pageDirection">
          <Page
            :total="total"
            :current.sync="page"
            :page-size.sync="pagesize"
            show-elevator
            show-sizer
            show-total
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
            :page-size-opts="[10, 20, 30, 40, 100]"
          >
          </Page>
        </div>
      </div>
    </div>
    <!-- 创建弹框 -->
    <Modal class="newModalClass echo_wrap" v-model="addModal" :width="700">
      <p slot="header">
        <span>程序创建</span>
      </p>
      <div class="modal_body">
        <div class="echo_row">
          <div class="filter">
            <label>
              <i>*</i>
              主程序号：
            </label>
            <Input class="searchInput" v-model="addObj.mainProgramNo" />
          </div>
          <div class="filter">
            <label>
              <i>*</i>
              主程序文件：
            </label>
            <Input
              v-if="addObj.mainProgramName"
              class="searchInput"
              icon="md-close-circle"
              :value="addObj.mainProgramName"
              @on-click="clearProgram('main')"
            />
            <Upload
              v-else
              class="upload echo_upload_btn searchInput"
              :action="action"
              :headers="headers"
              :show-upload-list="false"
              :format="fileFormat"
              :on-format-error="handleFormatError"
              :on-success="
                (r, f) => {
                  handleSuccess(r, f, 'main');
                }
              "
              :on-error="handleError"
            >
              <Button icon="ios-cloud-upload-outline">程序上传</Button>
            </Upload>
          </div>
          <span class="groupBtn" @click="addGroup()">+</span>
        </div>
        <div class="echo_row" v-for="(v, i) in addObj.childProgram" :key="i">
          <div class="filter">
            <label>
              <i>*</i>
              子程序号：
            </label>
            <Input class="searchInput" v-model="v.no" />
          </div>
          <div class="filter">
            <label>
              <i>*</i>
              子程序文件：
            </label>
            <Input
              v-if="v.name"
              class="searchInput"
              icon="md-close-circle"
              :value="v.name"
              @on-click="clearProgram(i)"
            />
            <Upload
              v-else
              class="upload echo_upload_btn searchInput"
              :action="action"
              :headers="headers"
              :show-upload-list="false"
              :format="fileFormat"
              :on-format-error="handleFormatError"
              :on-success="
                (r, f) => {
                  handleSuccess(r, f, i);
                }
              "
              :on-error="handleError"
            >
              <Button icon="ios-cloud-upload-outline">程序上传</Button>
            </Upload>
          </div>
          <span class="groupBtn" @click="delGroup(i)">-</span>
        </div>
        <div class="echo_row">
          <div class="filter">
            <label>
              <i>*</i>
              产品名称：
            </label>
            <Select
              v-model="addObj.productId"
              clearable
              filterable
              class="searchSelect"
              @on-change="handleProductChange"
            >
              <Option v-for="v in productList" :value="v.id" :key="v.id">{{
                v.name
              }}</Option>
            </Select>
          </div>
          <div class="filter">
            <label>
              <i>*</i>
              工序名称：
            </label>
            <Select
              v-model="addObj.routeId"
              clearable
              filterable
              class="searchSelect"
            >
              <Option v-for="v in routeList" :value="v.id" :key="v.id">{{
                v.name
              }}</Option>
            </Select>
          </div>
        </div>
        <div class="echo_row">
          <div class="filter">
            <label>
              <i>*</i>
              审核人员：
            </label>
            <Select
              v-model="addObj.checkBy"
              clearable
              filterable
              class="searchSelect"
            >
              <Option v-for="v in userList" :value="v.mid" :key="v.mid">{{
                v.name
              }}</Option>
            </Select>
          </div>
          <div class="filter">
            <label>备注：</label>
            <Input class="searchInput" v-model="addObj.remark" />
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="addModal = false">取消</Button>
        <Button v-if="preventDouble" size="large" type="primary" loading>
          确认
        </Button>
        <Button v-else size="large" type="primary" @click="confirmAdd()">
          确认
        </Button>
      </div>
    </Modal>
    <!-- 修改弹框 -->
    <Modal class="newModalClass echo_wrap" v-model="editModal" :width="700">
      <p slot="header">
        <span>程序修改</span>
      </p>
      <div class="modal_body">
        <div class="echo_row">
          <div class="filter">
            <label>
              <i>*</i>
              主程序号：
            </label>
            <Input class="searchInput" v-model="editObj.mainProgramNo" />
          </div>
          <div class="filter">
            <label>
              <i>*</i>
              主程序文件：
            </label>
            <Input
              v-if="editObj.mainProgramName"
              class="searchInput"
              icon="md-close-circle"
              :value="editObj.mainProgramName"
              @on-click="clearProgram('main')"
            />
            <Upload
              v-else
              class="upload echo_upload_btn searchInput"
              :action="action"
              :headers="headers"
              :show-upload-list="false"
              :format="fileFormat"
              :on-format-error="handleFormatError"
              :on-success="
                (r, f) => {
                  handleSuccess(r, f, 'main');
                }
              "
              :on-error="handleError"
            >
              <Button icon="ios-cloud-upload-outline">程序上传</Button>
            </Upload>
          </div>
          <span class="groupBtn" @click="addGroup()">+</span>
        </div>
        <div class="echo_row" v-for="(v, i) in editObj.childProgram" :key="i">
          <div class="filter">
            <label>
              <i>*</i>
              子程序号：
            </label>
            <Input class="searchInput" v-model="v.no" />
          </div>
          <div class="filter">
            <label>
              <i>*</i>
              子程序文件：
            </label>
            <Input
              v-if="v.name"
              class="searchInput"
              icon="md-close-circle"
              :value="v.name"
              @on-click="clearProgram(i)"
            />
            <Upload
              v-else
              class="upload echo_upload_btn searchInput"
              :action="action"
              :headers="headers"
              :show-upload-list="false"
              :format="fileFormat"
              :on-format-error="handleFormatError"
              :on-success="
                (r, f) => {
                  handleSuccess(r, f, i);
                }
              "
              :on-error="handleError"
            >
              <Button icon="ios-cloud-upload-outline">程序上传</Button>
            </Upload>
          </div>
          <span class="groupBtn" @click="delGroup(i)">-</span>
        </div>
        <div class="echo_row">
          <div class="filter">
            <label>
              <i>*</i>
              产品名称：
            </label>
            <Select
              v-model="editObj.productId"
              clearable
              filterable
              class="searchSelect"
            >
              <Option v-for="v in productList" :value="v.id" :key="v.id">{{
                v.name
              }}</Option>
            </Select>
          </div>
          <div class="filter">
            <label>
              <i>*</i>
              工序名称：
            </label>
            <Select
              v-model="editObj.routeId"
              clearable
              filterable
              class="searchSelect"
            >
              <Option v-for="v in routeList" :value="v.id" :key="v.id">{{
                v.name
              }}</Option>
            </Select>
          </div>
        </div>
        <div class="echo_row">
          <div class="filter">
            <label>
              <i>*</i>
              审核人员：
            </label>
            <Select
              v-model="editObj.checkBy"
              clearable
              filterable
              class="searchSelect"
            >
              <Option v-for="v in userList" :value="v.mid" :key="v.mid">{{
                v.name
              }}</Option>
            </Select>
          </div>
          <div class="filter">
            <label>备注：</label>
            <Input class="searchInput" v-model="editObj.remark" />
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="editModal = false">取消</Button>
        <Button size="large" type="primary" @click="confirmEdit()">确认</Button>
      </div>
    </Modal>
    <!-- 编辑弹框 -->
    <Modal class="newModalClass echo_wrap" v-model="contentModal" :width="900">
      <p slot="header">
        <span>编辑内容</span>
      </p>
      <div class="modal_body">
        <Tabs value="0" type="card">
          <TabPane
            v-for="(v, i) in contentList"
            :label="
              v.program_type == 1
                ? `主程序（${v.program_code}）`
                : `子程序（${v.program_code}）`
            "
            :name="`${i}`"
            :key="i"
          >
            <textarea class="echo_textarea" v-model="v.file_content"></textarea>
          </TabPane>
        </Tabs>
      </div>
      <div slot="footer">
        <Button size="large" @click="contentModal = false">取消</Button>
        <Button size="large" type="primary" @click="confirmEditContent()">
          确定
        </Button>
      </div>
    </Modal>
    <!-- 版本记录弹框 -->
    <Modal
      class="newModalClass echo_wrap versionModal"
      v-model="historyModal"
      :width="1000"
      footer-hide
    >
      <p slot="header">
        <span>版本记录</span>
      </p>
      <div class="modal_body">
        <div class="echo_row">
          <div class="filter">
            <label>产品名称：</label>
            <Input class="searchInput" :value="row.productname" readonly />
          </div>
          <div class="filter">
            <label>程序号：</label>
            <Input class="searchInput" :value="row.program_code" readonly />
          </div>
        </div>
        <div class="echo_row">
          <Table
            v-if="refresh"
            class="tableClass"
            :data="historyData"
            :columns="historyColumns"
            :max-height="500"
          >
          </Table>
        </div>
      </div>
    </Modal>
    <!-- 程序预览弹框 -->
    <Modal
      class="newModalClass echo_wrap"
      v-model="previewModal"
      :width="900"
      footer-hide
    >
      <p slot="header">
        <span>程序预览</span>
      </p>
      <div class="modal_body">
        <Tabs value="0" type="card">
          <TabPane
            v-for="(v, i) in previewList"
            :label="
              v.program_type == 1
                ? `主程序（${v.program_code}）`
                : `子程序（${v.program_code}）`
            "
            :name="`${i}`"
            :key="i"
          >
            <textarea class="echo_textarea" :value="v.file_content"></textarea>
          </TabPane>
        </Tabs>
      </div>
    </Modal>
  </div>
</template>

<script>
import moment from "moment";

export default {
  data() {
    return {
      tabIndex: 0,
      // 查询
      btnShow1: false,
      // 创建
      btnShow2: false,
      // 修改
      btnShow3: false,
      // 删除
      btnShow4: false,
      // 编辑内容
      btnShow5: false,
      // 下载
      btnShow6: false,
      // 版本记录
      btnShow7: false,
      // 搜索条件--程序号
      programNo: "",
      // 搜索条件--产品ID
      productId: "",
      // 产品下拉列表
      productList: [],
      // 审核人员下拉列表
      userList: [],
      // 搜索条件--审核状态
      auditStatus: "",
      // 页码，页距，总计
      page: 1,
      pagesize: 10,
      total: 0,
      // 表格数据
      tableData: [],
      // 当前选中行
      row: {},
      // 表格列字段
      tableColumns: [
        {
          type: "sort",
          title: "序号",
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
          width: 75,
          align: "center",
        },
        {
          title: "操作",
          width: 80,
          align: "center",
          render: (h, params) => {
            const _this = this;
            return h(
              "div",
              {
                style: {
                  textAlign: "center",
                  color: "#2D8CF0",
                  cursor: "pointer",
                },
                on: {
                  click: () => {
                    let row = params.row;
                    if (!row.program_version) {
                      _this.$Message.error("程序版本号不能为空！");
                      return;
                    }
                    _this.axios
                      .request({
                        url: "/dnc/DncPgCreate/GetAllContent",
                        params: {
                          programId: row.id,
                        },
                        method: "get",
                      })
                      .then((res) => {
                        let result = res.data;
                        if (result.ret == 1) {
                          _this.previewList = [];
                          let data = result.data;
                          if (data && Array.isArray(data) && data.length) {
                            _this.previewList = data;
                          }
                          _this.previewModal = true;
                        } else {
                          _this.$Message.error(_this.$t(result.msg));
                        }
                      });
                  },
                },
              },
              "预览"
            );
          },
        },
        {
          title: "主程序号",
          key: "program_code",
        },
        {
          title: "产品名称",
          key: "productname",
        },
        {
          title: "产品图纸号",
          key: "code",
        },
        {
          title: "工序名称",
          key: "process_name",
        },
        {
          title: "主程序文件名",
          key: "file_name",
          width: 120,
          align: "center",
        },
        {
          title: "创建人",
          key: "createname",
          width: 85,
          align: "center",
        },
        {
          title: "创建时间",
          key: "createtime",
          width: 150,
          align: "center",
        },
        {
          title: "创建备注",
          key: "create_remark",
          width: 90,
          align: "center",
        },
        {
          title: "审核人",
          key: "checkname",
          width: 85,
          align: "center",
        },
        {
          title: "审核时间",
          key: "checktime",
          width: 150,
          align: "center",
        },
        {
          title: "审核结果",
          key: "checkinfo",
          width: 90,
          align: "center",
          render: (h, params) => {
            let status = params.row.checkinfo;
            let text;
            switch (status) {
              case 0:
                text = "未审核";
                break;
              case 1:
                text = "通过";
                break;
              case 2:
                text = "不通过";
                break;
            }
            return h(
              "div",
              {
                style: {
                  textAlign: "center",
                },
              },
              text
            );
          },
        },
        {
          title: "审核备注",
          key: "check_remark",
          width: 90,
          align: "center",
        },
        {
          title: "子程序个数",
          key: "program_number",
          align: "center",
        },
        {
          title: "版本号",
          key: "program_version",
        },
        {
          title: "状态",
          align: "center",
          width: 90,
          render: (h, params) => {
            let bg, text;
            let status = params.row.checkstatus;
            switch (status) {
              case 1:
                text = "待审核";
                bg = "#FFFF00";
                break;
              case 2:
                text = "已审核";
                bg = "#00FF00";
                break;
              case 3:
                text = "被拒绝";
                bg = "#FF0000";
                break;
            }
            return h("div", {
              domProps: {
                innerHTML: text,
              },
              style: {
                backgroundColor: bg,
                width: "100%",
                height: "36px",
                lineHeight: "36px",
                textAlign: "center",
              },
            });
          },
        },
      ],
      // 创建对象
      addObj: {
        mainProgramNo: "",
        mainProgramPath: "",
        mainProgramName: "",
        mainProgramSize: 0,
        childProgram: [
          {
            no: "",
            path: "",
            name: "",
            size: 0,
          },
        ],
        productId: "",
        routeId: "",
        checkBy: "",
        remark: "",
      },
      // 创建弹框是否弹出
      addModal: false,
      // 修改对象
      editObj: {
        mainProgramNo: "",
        mainProgramPath: "",
        mainProgramName: "",
        mainProgramSize: 0,
        childProgram: [
          {
            no: "",
            path: "",
            name: "",
            size: 0,
          },
        ],
        productId: "",
        routeId: "",
        checkBy: "",
        remark: "",
      },
      // 修改弹框是否弹出
      editModal: false,
      // 操作类型 1 创建 2 修改
      type: 0,
      // 编辑内容弹框是否弹出
      contentModal: false,
      // 版本记录弹框是否弹出
      historyModal: false,
      // 版本记录表格数据
      historyData: [],
      // 版本记录表格列字段
      historyColumns: [
        {
          type: "sort",
          title: "序号",
          render: (h, params) => {
            return h(
              "span",
              params.index + 1 + (this.page - 1) * this.pagesize
            );
          },
        },
        {
          title: "文件名称",
          key: "file_name",
        },
        {
          title: "上传/更新时间",
          width: 150,
          align: "center",
          render: (h, params) => {
            let str = moment(params.row.create_time * 1000).format(
              "YYYY-MM-DD HH:mm:ss"
            );
            return h("div", {
              domProps: {
                innerHTML: str,
              },
              style: {
                textAlign: "center",
              },
            });
          },
        },
        {
          title: "上传人",
          key: "creater",
        },
        {
          title: "审核人",
          key: "checker",
        },
        {
          title: "生效版本",
          width: 85,
          align: "center",
          render: (h, params) => {
            const _this = this;
            let isActive = params.row.isUse;
            return h("Radio", {
              props: {
                value: isActive ? isActive : false,
              },
              style: {
                textAlign: "center",
              },
              on: {
                "on-change": () => {
                  _this.axios
                    .request({
                      url: "/dnc/DncPgCreate/ProgramVersionSwitch",
                      params: {
                        programCode: _this.row.program_code,
                        programId: params.row.id,
                      },
                      method: "get",
                    })
                    .then((res) => {
                      let result = res.data;
                      if (result.ret == 1) {
                        _this.$Message.success(_this.$t(result.msg));
                        _this.historyModal = false;
                        _this.search();
                      } else {
                        _this.$Message.error(_this.$t(result.msg));
                      }
                    });
                },
              },
            });
          },
        },
        {
          title: "版本号",
          key: "program_version",
        },
        {
          title: "操作",
          width: 85,
          align: "center",
          render: (h, params) => {
            const _this = this;
            return h(
              "div",
              {
                style: {
                  textAlign: "center",
                  color: "#3333FF",
                  cursor: "pointer",
                },
                on: {
                  click: () => {
                    _this.axios
                      .request({
                        url: `/dnc/DncPgCreate/DownloadZipById?programId=${params.row.id}`,
                        data: {
                          programId: params.row.id,
                        },
                        method: "post",
                      })
                      .then((res) => {
                        let result = res.data;
                        if (result.ret == 1) {
                          window.location.href =
                            _this.axios.publicPath + result.data;
                        } else {
                          _this.$Message.error(_this.$t(result.msg));
                        }
                      });
                  },
                },
              },
              "下载"
            );
          },
        },
      ],
      // 预览弹框是否弹出
      previewModal: false,
      // 工序下拉列表
      routeList: [],
      // 程序预览数据列表
      previewList: [],
      // 编辑内容数据列表
      contentList: [],
      refresh: false,
      // 防抖
      preventDouble: false,
    };
  },
  computed: {
    // 文件上传地址
    action() {
      const _this = this;
      let url = _this.axios.publicPath + "dnc/DncPgCreate/Upload";
      return url;
    },
    // 文件上传请求头
    headers() {
      return {
        token: localStorage.getItem("token"),
        timestamp: localStorage.getItem("timestamp"),
        nonce: localStorage.getItem("nonce"),
        sign: localStorage.getItem("sign"),
      };
    },
    // 文件上传允许的格式
    fileFormat() {
      return ["txt", "eia", "mpf", "min", "spf", "cnc", "nc", "prg"];
    },
  },
  mounted() {
    const _this = this;
    // 格式化表格样式
    this.tableColumns = this.$time.initTableTitle(this.tableColumns);
    this.historyColumns = this.$time.initTableTitle(this.historyColumns);
    // 获取产品下拉列表
    this.getProductList();
    // 获取审核人员下拉列表
    this.getUserList();
    // 初始化查询
    this.search();
    // 获取按钮组权限
    this.getBtnPermission();
    // 监听向左向右按钮事件
    // document.onkeydown = function (event) {
    //   console.log(event);
    //   let keyCode = 0,
    //     e = e || event;
    //   keyCode = e.keyCode || e.which || e.charCode;
    //   let keyName = String.fromCharCode(keyCode);
    //   switch (keyCode) {
    //     case 37:
    //       _this.tabIndex--;
    //       console.log(_this.tabIndex);
    //       break;
    //     case 39:
    //       _this.tabIndex++;
    //       break;
    //   }
    // };
  },
  methods: {
    // 获取按钮组权限
    getBtnPermission() {
      const _this = this;

      _this.axios
        .request({
          url: "/dnc/DncPgCreate/GetCheckbuttons",
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let permission = result.data;
            if (permission.addpower == 1) {
              _this.btnShow1 = true;
              _this.btnShow2 = true;
              _this.btnShow3 = true;
              _this.btnShow5 = true;
              _this.btnShow6 = true;
              _this.btnShow7 = true;
            }
            if (permission.delpower == 1) {
              _this.btnShow1 = true;
              _this.btnShow4 = true;
              _this.btnShow6 = true;
              _this.btnShow7 = true;
            }
            if (permission.allpower == 1) {
              _this.btnShow1 = true;
              _this.btnShow2 = true;
              _this.btnShow3 = true;
              _this.btnShow4 = true;
              _this.btnShow5 = true;
              _this.btnShow6 = true;
              _this.btnShow7 = true;
            }
          }
        });
    },
    // 获取产品下拉列表
    getProductList() {
      const _this = this;
      _this.axios
        .request({
          url: "/config/ProjectProduct/GetProductsByCode?code=&name=&count=50",
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.productList = [];
            if (data && Array.isArray(data) && data.length) {
              _this.productList = data;
            }
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 查询
    search(isInit) {
      const _this = this;
      if (isInit) {
        _this.page = 1;
        _this.pagesize = 10;
      }
      let { programNo, productId, auditStatus, page, pagesize } = this;
      let params = {
        productId: productId,
        programCode: programNo,
        checkStatus: auditStatus ? auditStatus : 0,
        page,
        pagesize,
      };
      _this.axios
        .request({
          url: "/dnc/DncPgCreate/GetProgramsLists",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.total = result.total;
            _this.tableData = [];
            let data = result.data;
            if (data && Array.isArray(data) && data.length) {
              _this.tableData = data;
            }
          }
        });
    },
    // 监听表格当前选中行
    handleRowChange(cur) {
      this.row = cur;
    },
    // 监听页码变化
    handlePage(v) {
      this.page = v;
      this.search();
    },
    // 监听页距变化
    handlePageSize(v) {
      this.page = 1;
      this.pagesize = v;
      this.search();
    },
    // 监听文件上传格式错误钩子
    handleFormatError(file) {
      this.$Message.error(this.$t(888822));
    },
    // 监听文件上传成功钩子
    handleSuccess(res, file, params) {
      const _this = this;
      let { type } = this;
      if (res.ret == 1) {
        this.$Message.success(this.$t(888823));
        let data = res.data;
        if (params == "main") {
          if (type == 1) {
            _this.$set(_this.addObj, "mainProgramPath", data.file_url);
            _this.$set(_this.addObj, "mainProgramName", data.name);
            _this.$set(_this.addObj, "mainProgramSize", data.size);
          } else if (type == 2) {
            _this.$set(_this.editObj, "mainProgramPath", data.file_url);
            _this.$set(_this.editObj, "mainProgramName", data.name);
            _this.$set(_this.editObj, "mainProgramSize", data.size);
          }
        } else {
          if (type == 1) {
            _this.$set(
              _this.addObj.childProgram[params],
              "path",
              data.file_url
            );
            _this.$set(_this.addObj.childProgram[params], "name", data.name);
            _this.$set(_this.addObj.childProgram[params], "size", data.size);
          } else if (type == 2) {
            _this.$set(
              _this.editObj.childProgram[params],
              "path",
              data.file_url
            );
            _this.$set(_this.editObj.childProgram[params], "name", data.name);
            _this.$set(_this.editObj.childProgram[params], "size", data.size);
          }
        }
      } else {
        this.$Message.error(this.$t(res.msg));
      }
    },
    // 监听文件上传失败钩子
    handleError() {
      this.$Message.error(this.$t(888824));
    },
    // 清除上传文件
    clearProgram(params) {
      const _this = this;
      let { type } = this;
      if (params == "main") {
        if (type == 1) {
          _this.addObj.mainProgramName = "";
          _this.addObj.mainProgramPath = "";
          _this.addObj.mainProgramSize = 0;
        } else if (type == 2) {
          _this.editObj.mainProgramName = "";
          _this.editObj.mainProgramPath = "";
          _this.editObj.mainProgramSize = 0;
        }
      } else {
        if (type == 1) {
          _this.addObj.childProgram[params].name = "";
          _this.addObj.childProgram[params].path = "";
          _this.addObj.childProgram[params].size = 0;
        } else if (type == 2) {
          _this.editObj.childProgram[params].name = "";
          _this.editObj.childProgram[params].path = "";
          _this.editObj.childProgram[params].size = 0;
        }
      }
    },
    // 添加一组子程序
    addGroup() {
      const _this = this;
      let { type } = this;
      if (type == 1) {
        _this.addObj.childProgram.push({
          no: "",
          name: "",
          path: "",
          size: 0,
        });
      } else if (type == 2) {
        _this.editObj.childProgram.push({
          no: "",
          name: "",
          path: "",
          size: 0,
        });
      }
    },
    // 删除一组子程序
    delGroup(i) {
      const _this = this;
      let { type } = this;
      if (type == 1) {
        _this.addObj.childProgram.splice(i, 1);
      } else if (type == 2) {
        _this.editObj.childProgram.splice(i, 1);
      }
    },
    // 点击创建
    add() {
      // 清空上次输入数据
      this.addObj = {
        mainProgramNo: "",
        mainProgramPath: "",
        mainProgramName: "",
        mainProgramSize: 0,
        childProgram: [
          {
            no: "",
            path: "",
            name: "",
            size: 0,
          },
        ],
        productId: "",
        routeId: "",
        checkBy: "",
        remark: "",
      };
      this.type = 1;
      // 弹框弹出
      this.addModal = true;
      this.preventDouble = false;
    },
    // 获取审核人员下拉列表
    getUserList() {
      const _this = this;
      _this.axios
        .request({
          url: "/dnc/DncPgCreate/GetCheckUsers",
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.userList = [];
            if (data && Array.isArray(data) && data.length) {
              _this.userList = data;
            }
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 点击修改
    edit() {
      const _this = this;
      let { row } = this;
      if (JSON.stringify(row) == "{}") {
        _this.$Message.error(_this.$t(1043));
        return;
      }
      let params = {
        programid: row.id,
      };
      _this.axios
        .request({
          url: "/dnc/DncPgCreate/GetMainProgramInfo",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data[0];
            let mainProgramNo,
              mainProgramPath,
              mainProgramName,
              mainProgramSize,
              mainProgramId;
            let childProgram = [];
            data.programs.forEach((v) => {
              if (v.program_type == 1) {
                mainProgramNo = v.programcode;
                mainProgramPath = v.file_url;
                mainProgramName = v.file_name;
                mainProgramSize = v.file_size;
                mainProgramId = v.programid;
              } else {
                childProgram.push({
                  no: v.programcode,
                  path: v.file_url,
                  name: v.file_name,
                  size: v.file_size,
                  id: v.programid,
                });
              }
            });
            _this.editObj = {
              mainProgramNo: mainProgramNo,
              mainProgramPath: mainProgramPath,
              mainProgramName: mainProgramName,
              mainProgramSize: mainProgramSize,
              childProgram: childProgram,
              productId: data.productid,
              routeId: data.processid,
              checkBy: data.checkmid,
              remark: data.createremark,
            };
            _this.handleProductChange(data.productid);
            this.type = 2;
            // 弹框弹出
            _this.editModal = true;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 点击删除
    del() {
      const _this = this;
      let { row, $t } = this;
      if (JSON.stringify(row) == "{}") {
        _this.$Message.error($t(1043));
        return;
      }
      let data = {
        programid: row.id,
      };
      _this.$Modal.confirm({
        title: $t(1018),
        content: "",
        width: 300,
        closable: true,
        okText: $t(1004),
        onOk: () => {
          _this.axios
            .request({
              url: `/dnc/DncPgCreate/DelAllProgram?programid=${row.id}`,
              data,
              method: "post",
            })
            .then((res) => {
              let result = res.data;
              if (result.ret == 1) {
                _this.$Message.success($t(result.msg));
                _this.page = 1;
                _this.search();
              } else {
                _this.$Message.error($t(result.msg));
              }
            });
        },
      });
    },
    // 点击编辑
    editProgram() {
      const _this = this;
      let { row, $t } = this;
      if (JSON.stringify(row) == "{}") {
        _this.$Message.error($t(1043));
        return;
      }
      _this.axios
        .request({
          url: "/dnc/DncPgCreate/GetAllContent",
          params: {
            programId: row.id,
          },
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.contentList = [];
            let data = result.data;
            if (data && Array.isArray(data) && data.length) {
              _this.contentList = data;
            }
            _this.contentModal = true;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 确认修改程序内容
    confirmEditContent() {
      const _this = this;
      let { contentList } = this;
      let arr = [];
      contentList.forEach((v) => {
        arr.push({
          id: v.programid,
          content: v.file_content,
        });
      });
      let data = {
        allcontent: arr,
      };
      _this.axios
        .request({
          url: "/dnc/DncPgCreate/UpdateProgramAllContent",
          data,
          method: "post",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success(_this.$t(result.msg));
            _this.contentModal = false;
            _this.search();
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 下载方法
    funDownload(content, filename) {
      // 创建隐藏的可下载链接
      var eleLink = document.createElement("a");
      eleLink.download = filename;
      eleLink.style.display = "none";
      // 字符内容转变成blob地址
      var blob = new Blob([content]);
      eleLink.href = URL.createObjectURL(blob);
      // 触发点击
      document.body.appendChild(eleLink);
      eleLink.click();
      // 然后移除
      document.body.removeChild(eleLink);
    },
    // 点击下载
    download() {
      const _this = this;
      let { row, $t } = this;
      if (JSON.stringify(row) == "{}") {
        _this.$Message.error($t(1043));
        return;
      }
      if (!row.file_url) {
        _this.$Message.error($t(9000147));
        return;
      }
      _this.axios
        .request({
          url: `/dnc/DncPgCreate/DownloadZipById?programId=${row.id}`,
          data: {
            programId: row.id,
          },
          method: "post",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            window.location.href = _this.axios.publicPath + result.data;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 点击版本记录
    getHistory() {
      const _this = this;
      let { row, $t } = this;
      if (JSON.stringify(row) == "{}") {
        _this.$Message.error($t(1043));
        return;
      }

      let params = {
        programCode: row.program_code,
        pagesize: 666666,
      };

      _this.refresh = false;

      _this.axios
        .request({
          url: "/dnc/DncPgCreate/GetProgramVersionRecord",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.historyData = [];
            let data = result.data;
            if (data && Array.isArray(data) && data.length) {
              _this.historyData = data;
            }
            _this.refresh = true;
            _this.historyModal = true;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 监听产品选择变化
    handleProductChange(v) {
      if (!v) {
        return;
      }
      const _this = this;
      let params = {
        productId: v,
      };
      _this.axios
        .request({
          url: "/config/ProductRoute/GetRoutesByProduct",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.routeList = [];
            let data = result.data;
            if (data && Array.isArray(data) && data.length) {
              _this.routeList = data;
            }
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 确认创建
    confirmAdd() {
      const _this = this;
      let { addObj, $t } = this;
      if (!addObj.mainProgramNo) {
        _this.$Message.error("请输入主程序号！");
        return;
      }
      if (!/^[a-z0-9]+$/i.test(addObj.mainProgramNo)) {
        _this.$Message.error("程序号禁止特殊字符！");
        return;
      }
      if (!addObj.mainProgramName) {
        _this.$Message.error("请上传主程序文件！");
        return;
      }
      for (let i = 0; i < addObj.childProgram.length; i++) {
        if (!addObj.childProgram[i].no) {
          _this.$Message.error("请输入子程序号！");
          return;
        }
        if (!/^[a-z0-9]+$/i.test(addObj.childProgram[i].no)) {
          _this.$Message.error("程序号禁止特殊字符！");
          return;
        }
        if (!addObj.childProgram[i].name) {
          _this.$Message.error("请上传子程序文件！");
          return;
        }
      }
      if (!addObj.productId) {
        _this.$Message.error("请选择产品名称！");
        return;
      }
      if (!addObj.routeId) {
        _this.$Message.error("请选择工序名称！");
        return;
      }
      if (!addObj.checkBy) {
        _this.$Message.error("请选择审核人员！");
        return;
      }
      _this.preventDouble = true;
      _this.axios
        .request({
          url: "/dnc/DncPgCreate/CheckprogramCodeMainPost",
          params: {
            programcode: addObj.mainProgramNo,
          },
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            // 没有重复的主程序号 直接添加
            let programs = [];
            programs.push({
              file_url: addObj.mainProgramPath,
              file_name: addObj.mainProgramName,
              file_size: addObj.mainProgramSize,
              programcode: addObj.mainProgramNo,
              program_type: 1,
            });
            addObj.childProgram.forEach((v) => {
              programs.push({
                file_url: v.path,
                file_name: v.name,
                file_size: v.size,
                programcode: v.no,
                program_type: 2,
              });
            });
            let data = {
              programs: programs,
              productid: addObj.productId ? addObj.productId : 0,
              checkmid: addObj.checkBy ? addObj.checkBy : 0,
              createremark: addObj.remark,
              process_code: addObj.routeId ? addObj.routeId : "",
            };
            _this.axios
              .request({
                url: "/dnc/DncPgCreate/AddProgramPosts",
                data,
                method: "post",
              })
              .then((res) => {
                let result = res.data;
                if (result.ret == 1) {
                  _this.$Message.success(_this.$t(result.msg));
                  _this.addModal = false;
                  _this.page = 1;
                  _this.pagesize = 10;
                  _this.search();
                } else {
                  _this.$Message.error(_this.$t(result.msg));
                }
                _this.preventDouble = false;
              })
              .catch((err) => {
                _this.preventDouble = false;
              });
          } else {
            // 有重复的主程序号，由用户决定是否继续添加
            _this.$Modal.confirm({
              title: $t(result.msg),
              content: "",
              width: 400,
              closable: true,
              okText: $t(1011),
              onOk: () => {
                let programs = [];
                programs.push({
                  file_url: addObj.mainProgramPath,
                  file_name: addObj.mainProgramName,
                  file_size: addObj.mainProgramSize,
                  programcode: addObj.mainProgramNo,
                  program_type: 1,
                });
                addObj.childProgram.forEach((v) => {
                  programs.push({
                    file_url: v.path,
                    file_name: v.name,
                    file_size: v.size,
                    programcode: v.no,
                    program_type: 2,
                  });
                });
                let data = {
                  programs: programs,
                  productid: addObj.productId ? addObj.productId : 0,
                  checkmid: addObj.checkBy ? addObj.checkBy : 0,
                  createremark: addObj.remark,
                  process_code: addObj.routeId ? addObj.routeId : "",
                };
                _this.axios
                  .request({
                    url: "/dnc/DncPgCreate/AddProgramPosts",
                    data,
                    method: "post",
                  })
                  .then((res) => {
                    let result = res.data;
                    if (result.ret == 1) {
                      _this.$Message.success(_this.$t(result.msg));
                      _this.addModal = false;
                      _this.page = 1;
                      _this.pagesize = 10;
                      _this.search();
                    } else {
                      _this.$Message.error(_this.$t(result.msg));
                    }
                    _this.preventDouble = false;
                  })
                  .catch((err) => {
                    _this.preventDouble = false;
                  });
              },
              onCancel: () => {
                _this.preventDouble = false;
              },
            });
          }
        })
        .catch((err) => {
          _this.preventDouble = false;
        });
    },
    // 确认修改
    confirmEdit() {
      const _this = this;
      let { editObj, $t } = this;
      if (!editObj.mainProgramNo) {
        _this.$Message.error("请输入主程序号！");
        return;
      }
      if (!/^[a-z0-9]+$/i.test(editObj.mainProgramNo)) {
        _this.$Message.error("程序号禁止特殊字符！");
        return;
      }
      if (!editObj.mainProgramName) {
        _this.$Message.error("请上传主程序文件！");
        return;
      }
      for (let i = 0; i < editObj.childProgram.length; i++) {
        if (!editObj.childProgram[i].no) {
          _this.$Message.error("请输入子程序号！");
          return;
        }
        if (!/^[a-z0-9]+$/i.test(editObj.childProgram[i].no)) {
          _this.$Message.error("程序号禁止特殊字符！");
          return;
        }
        if (!editObj.childProgram[i].name) {
          _this.$Message.error("请上传子程序文件！");
          return;
        }
      }
      if (!editObj.productId) {
        _this.$Message.error("请选择产品名称！");
        return;
      }
      if (!editObj.routeId) {
        _this.$Message.error("请选择工序名称！");
        return;
      }
      if (!editObj.checkBy) {
        _this.$Message.error("请选择审核人员！");
        return;
      }
      _this.axios
        .request({
          url: "/dnc/DncPgCreate/CheckprogramCodeMainPost",
          params: {
            programcode: editObj.mainProgramNo,
          },
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            // 没有重复的主程序号 直接修改
            let programs = [];
            programs.push({
              file_url: editObj.mainProgramPath,
              file_name: editObj.mainProgramName,
              file_size: editObj.mainProgramSize,
              programcode: editObj.mainProgramNo,
              program_type: 1,
              programid: editObj.mainProgramId,
            });
            editObj.childProgram.forEach((v) => {
              programs.push({
                programid: v.id,
                file_url: v.path,
                file_name: v.name,
                file_size: v.size,
                programcode: v.no,
                program_type: 2,
              });
            });
            let data = {
              programid: _this.row.id,
              programs: programs,
              productid: editObj.productId ? editObj.productId : 0,
              checkmid: editObj.checkBy ? editObj.checkBy : 0,
              createremark: editObj.remark,
              process_code: editObj.routeId ? editObj.routeId : "",
            };
            data.process_code = String(data.process_code);
            _this.axios
              .request({
                url: "/dnc/DncPgCreate/EditProgram",
                data,
                method: "post",
              })
              .then((res) => {
                let result = res.data;
                if (result.ret == 1) {
                  _this.$Message.success(_this.$t(result.msg));
                  _this.editModal = false;
                  _this.search();
                } else {
                  _this.$Message.error(_this.$t(result.msg));
                }
              });
          } else {
            // 有重复的主程序号，由用户决定是否继续添加
            _this.$Modal.confirm({
              title: $t(result.msg),
              content: "",
              width: 400,
              closable: true,
              okText: $t(1011),
              onOk: () => {
                let programs = [];
                programs.push({
                  file_url: editObj.mainProgramPath,
                  file_name: editObj.mainProgramName,
                  file_size: editObj.mainProgramSize,
                  programcode: editObj.mainProgramNo,
                  program_type: 1,
                  programid: editObj.mainProgramId,
                });
                editObj.childProgram.forEach((v) => {
                  programs.push({
                    programid: v.id,
                    file_url: v.path,
                    file_name: v.name,
                    file_size: v.size,
                    programcode: v.no,
                    program_type: 2,
                  });
                });
                let data = {
                  programid: _this.row.id,
                  programs: programs,
                  productid: editObj.productId ? editObj.productId : 0,
                  checkmid: editObj.checkBy ? editObj.checkBy : 0,
                  createremark: editObj.remark,
                  process_code: editObj.routeId ? editObj.routeId : "",
                };
                data.process_code = String(data.process_code);
                _this.axios
                  .request({
                    url: "/dnc/DncPgCreate/EditProgram",
                    data,
                    method: "post",
                  })
                  .then((res) => {
                    let result = res.data;
                    if (result.ret == 1) {
                      _this.$Message.success(_this.$t(result.msg));
                      _this.editModal = false;
                      _this.search();
                    } else {
                      _this.$Message.error(_this.$t(result.msg));
                    }
                  });
              },
            });
          }
        });
    },
  },
};
</script>

<style lang="less" scoped>
.echo_textarea::-webkit-scrollbar {
  width: auto;
}
.echo_textarea {
  font-size: 14px;
  white-space: nowrap;
  overflow: auto;
  resize: none;
  width: 100%;
  height: 444px;
}
.groupBtn {
  width: 32px;
  height: 32px;
  background: rgb(87, 163, 243);
  color: rgb(255, 255, 255);
  display: inline-block;
  vertical-align: top;
  font-size: 20px;
  text-align: center;
  border-radius: 3px;
  margin-left: 5px;
  width: 30px;
  height: 30px;
  background: #57a3f3;
  color: #fff;
  cursor: pointer;
}
.upload {
  display: inline-block;
}
.expand-row {
  margin-bottom: 16px;
}
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
.ivu-input-word-count {
  text-align: center;
  position: absolute;
  right: 7px;
  bottom: 2px;
  padding-left: 7px;
  background: #fff;
  z-index: 1;
  display: inline-flex;
  color: #808695;
  font-size: 12px;
}
</style>
